问题:
有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
解题思路:
假设一共有n个人,则定义一个长度为n的boolean数组。全部元素的值为true。报数为3的元素其值为false。一直循环下去,直到只剩下一个值为true的元素。则该原色的下标加一就是最后剩下的人的号码。
下面是代码:
package com.test;/** * 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下 * * 的是原来第几号的那位。 * * @author Administrator * */public class Test19CallNumber { public static void main(String[] args) { boolean[] persons = doCall(10); 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; key = 0; } } } number = 0; for (int i = 0; i < person; i++) { if (persons[i]) { number++; } } } return persons; }}
最后测试结果是正确的。
下面是测试结果:
编号为:3的人退出。编号为:6的人退出。编号为:9的人退出。编号为:2的人退出。编号为:7的人退出。编号为:1的人退出。编号为:8的人退出。编号为:5的人退出。编号为:10的人退出。最后留下的是:4号。
一个风向” 博客,请务必保留此出处http://lanffy.blog.51cto.com/6452125/1339318
没有创造的生活不能算生活,只能算活着。