题目:100个人手拉手围成一圈,逢三退一(1到3循环数数,被数到3的人退出),求最后一个被剩下人的编号,请写出代码。
c#代码:
static void Main(string[] args)
{
List<int> childList = new List<int>(); //定义集合
//给集合赋值,100个元素,从1赋值到100,代表100个小朋友的编号
for (int i = 0; i < 100; i++)
{
childList.Add(i + 1);
}
int count = 0; //表示报数结果
int index = 0; //表示为哪个小朋友报数0~99号小朋友
//注意:0号小朋友,编号为1,后面以此类推
//只有集合的元素个数大于1,即至少2个小朋友以上 才会执行该循环
while (childList.Count > 1)
{
count++; //首先报数
if (count == 3) //判断报数是否为3
{
count = 0; //报数清0,准备下一次报数
childList.RemoveAt(index); //将当前index指向的小朋友移除
}
else
{
index++; //报数不为3,则index累加,指向下一个准备报数的小朋友
}
/*
* 无论报数结果是否为3,
* 最后都要判断index指向的小朋友,是否超出范围
* 若超出范围,则重新指向第一个小朋友
*/
if (index == childList.Count)
{
index = 0;
}
}
Console.WriteLine(childList[0]); //将最后一个剩下的小朋友的编号打印出来
Console.ReadLine();
}
执行结果:91