您的位置:首页 > 其它

n个人围一圈报数问题

2015-12-10 10:44 375 查看
题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。

运行结果:



/**
* @author Administrator
*N个人由N个Int型数值表示,每个Int值代表一个人
*每个人报的数存放在Int值中,可能为1~COUNT
*如果代表某人的Int值为COUNT,则表示退出圈子,不再参与报数
*一直循环,对所有非COUNT值的人报数,直到剩下最后一个人为止
*/
public class CountOff {
//N表示报数的人数
//COUNT表示从1报到COUNT
//loop表示报到剩最后一个人时,总共报了多少次数
static int N = 40 , COUNT = 3, loop=0;
static int[] people = new int
;
public static void main(String[] args) {
int i = countOff(people);
print(people);
System.out.println("loop:"+loop);
System.out.printf("%d个人报数,第%d个人是最后一个",N,i+1);
}

static int countOff(int[] people ) {
int len = people.length;
int off = 0;//退出圈子的人数
int c = 1;//报数值 1~COUNT
int i = 0;
while (true) {
if (people[i] != COUNT) {
people[i] = c++;
loop++;
if (c == COUNT+1) {
c = 1;
off++;//报到最后一个数COUNT,表明有一人退出
if (off == len-1) break;
}
}
i++;
if (i == len) i=0;
}

i = 0;
while (true) {
if (people[i] != COUNT) break;
i++;
}
return i;
}

static void print(int[] people) {
int n = 1;
for (int i : people) {
System.out.printf("%d ",i);
if (n++ % 10 == 0)
System.out.println();
}
System.out.println();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: