需求:
1-100号人,围成一个圈,从1号报数,123、123...报数,报3出圈圈,缩小圈圈,问最后留下那个人是多少号?
people=[]
a = 1
# 初始化数组
while a <= 100:
people.append(a)
a += 1
index = 1
# 开始报数
while True:
if people[-1] == people[0]:
break
if index == 4:
index = 1
continue
if index == 3:
# 出队列
del people[0]
else:
# 出队列后又重新入队列
people.append(people[0])
del people[0]
index += 1
print(people)
结果:

Java实现
public static void main(String[] args) {
List<Integer> list = new LinkedList<>();
for (int i = 1; i <= 100; i++) {
list.add(i);
}
int index = 1;
while (true) {
if (index == 4) {
index = 1;
}
if (list.size() == 1) {
break;
}
if (index == 3) {
list.remove(0);
} else {
list.add(list.get(0));
list.remove(0);
}
index++;
}
System.out.println(list);
}

网友评论