一群小孩围成一个圈,从第一个开始报数,报到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#经典面试题。 大家如果有更好的方法,麻烦分享一下,大家一起进步。