有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出,问最后留下的那位是原来第几号。
思路分析:首先是选好数据结构,轻量级的boolean数组,下边代表序号,全部初始化位true
退出变为false,设置全局变量int a,遍历数组,a (当对应为false时候,continue跳过)
遍历数组统计true的数量,为1时候退出
如果要用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;
}
}