n个人围一圈报数问题

题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
运行结果:
这里写图片描述

/**
 * @author Administrator
 *N个人由N个Int型数值表示,每个Int值代表一个人
 *每个人报的数存放在Int值中,可能为1~COUNT
 *如果代表某人的Int值为COUNT,则表示退出圈子,不再参与报数
 *一直循环,对所有非COUNT值的人报数,直到剩下最后一个人为止
 */
public class CountOff {
    //N表示报数的人数 
    //COUNT表示从1报到COUNT
    //loop表示报到剩最后一个人时,总共报了多少次数
    static int N = 40 , COUNT = 3, loop=0;
    static int[] people = new int[N]; 
    public static void main(String[] args) {
        int i = countOff(people);
        print(people);
        System.out.println("loop:"+loop);
        System.out.printf("%d个人报数,第%d个人是最后一个",N,i+1);
    }

    static int countOff(int[] people ) {
        int len = people.length;
        int off = 0;//退出圈子的人数
        int c = 1;//报数值 1~COUNT
        int i = 0;
        while (true) {
            if (people[i] != COUNT) {
                people[i] = c++; 
                loop++;
                if (c == COUNT+1) {
                    c = 1;
                    off++;//报到最后一个数COUNT,表明有一人退出
                    if (off == len-1) break;
                }
            }
            i++;
            if (i == len) i=0;
        }

        i = 0;
        while (true) {
            if (people[i] != COUNT) break;
            i++;
        }
        return i;
    }

    static void print(int[] people) {
        int n = 1;
        for (int i : people) {
            System.out.printf("%d ",i);
            if (n++ % 10 == 0)
                System.out.println();
        }
        System.out.println();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值