C#面試題:一群小孩圍成一個圈的經典演算法
阿新 • • 發佈:2018-12-26
一群小孩圍成一個圈,從第一個開始報數,報到5的小孩退出圈,繼續,求剩下的最後一個小孩的編號。
程式碼如下:
- public static int count = 0;//計數器
- public static int target = 5;//指定編號
- public static void Main (string[] args)
- {
- ArrayList all = new ArrayList ();//集合儲存全部小孩
- ArrayList dela = new ArrayList ();//集合儲存退出圈的小孩
- for (int i = 1; i <= 100; i++) {
- all.Add (i);//所有小孩新增到all集合中
- }
- while (true) {
- //如果只剩一個就退出
- if (all.Count == 1) {
- break;
- }
- foreach (var a in all) {
- count++;
- if (count == target) {
- count = 0;
- dela.Add (a);//退出圈的小孩新增到dela集合中
- }
- }
- foreach (var a in dela) {
- all.Remove (a);//退出圈的小孩從all集合中刪除
- }
- foreach (var a in all) {
- Console.WriteLine (a);//最後剩下的小孩
- }
- }
- }
這是一道C#經典面試題。 大家如果有更好的方法,麻煩分享一下,大家一起進步。