标签:
有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出,问最后留下的那位是原来第几号。
如果要用List来存储,注意遍历remove删除时候,要一致,不能list和iterator混用
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class Main {
static int all = 1;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
int input = scan.nextInt();
if(input < 1){
return;
}else{
boolean[] persons = doCall(input);
for (int i = 0; i < persons.length; i++) {
if (persons[i]) {
System.out.println("最后留下的是:"+(i+1)+"号。");
}
}
}
}
}
public static boolean[] doCall(int person) {
boolean[] persons = new boolean[person];
int number = person, key = 0;
for (int i = 0; i < person; i++)
persons[i] = true;
while (number != 1) {
for (int i = 0; i < person; i++) {
if (!persons[i]) {
continue;
} else {
key++;
if (key % 3 == 0) {
System.out.println("编号为:"+(i+1)+"的人退出。");
persons[i] = false;
}
}
}
number = 0;
for (int i = 0; i < person; i++) {
if (persons[i]) {
number++;
}
}
}
return persons;
}
}
标签:
原文地址:http://blog.csdn.net/lpjishu/article/details/51868827