有10个人围成一-圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是第几号的人。
public class LeftNumber {
public static void main(String[] args) {
int value = LeftNumber(1);
System.out.println(value);
}
public static int LeftNumber(int count) {
if (count <= 0) {
throw new IllegalArgumentException("人数必须大于0");
}
boolean[] status = new boolean[count];
for (int i = 0; i < status.length; i++) {
status[i] = true;
}
int index = -1;
int counter = 0; //当前退出的人数 n-1
int current = 0; //当前人报的数
while (counter < status.length - 1) {
//index 成环
index = (index + 1) % status.length;//0
if (!status[index]) {
continue;
}
//报数
current = (current + 1) % 3; //1
//退出
if (current == 0) {
counter++;
status[index] = false;
}
}
for (int i = 0; i < status.length; i++) {
if (status[i]) {
return i + 1;//1-n 0-(n-1)
}
}
throw new RuntimeException("未找到!!!");
}
}
这是一个典型的猴子大王的算法题,示例代码:
public static void main(String[] args) {
//1.定义长度为10的数组保存10个人
boolean[] b = new boolean[10];
//2.依次遍历每一个人
//true---未退出 false---已退出
for (int i = 0; i < b.length; i++) {
b[i] = true;//先把所有人设置成未退出
}
//3.定义变量保存所有人报的数
int num = 0;
//4.定义变量保存剩余的人数
int left = 10;
//5.定义数组下标
int index = 0;
//6.循环,直到只剩最后一个人
while (left > 1) {//判断条件
//7.检测是否已退出
if (b[index]) {
//8.报数
num++;
//9.判断报数是否为7
if (num == 3) {
b[index] = false;//为3退出
left--;//人数减一
num = 0;//报数归零
}
}
//10.下标移动
index++;
//11.围成一圈---最后一个置为0
if (index == 10) {
index = 0;
}
}
//遍历数组,找到最后剩的人
for (int i = 0; i < b.length; i++) {
if (b[i]) {
System.out.println(i + 1);
}
}
}
可以参考我的博客:https://blog.csdn.net/zhanglide0526/article/details/120754067?spm=1001.2014.3001.5502