n个人围成一圈报数,从1开始,凡是报到3的退出,最后留下的是几号?

xiaoxiao2021-02-28  15

题目:n个人围成一圈报数,从1开始,凡是报到3的推出,最后留下的是几号?

普通代码:

public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("请输入总人数:"); int p = input.nextInt(); //初始化人数组 boolean[] pre = new boolean[p]; for(int i=0;i<pre.length;i++){ pre[i]=true; } int t=0;int len = pre.length; while(len>1){ for(int i=0;i<pre.length;i++){ if(pre[i]){ t++; if(t==3){ t=0; pre[i]=false; len--; } } } } for(int i=0;i<pre.length;i++){ if(pre[i]){ System.out.println("最后一个人是:"+(i+1)+" 号"); } } }

 

 

 

神级代码(摘抄):

 

public static void main(String[] args) { System.out.println(cycle(5, 3)); } public static int cycle(int people, int num) { int i, r = 0; for (i = 2; i <= people; i++) r = (r + num) % i; return r + 1; }

 

 

 

 

 

 

转载请注明原文地址: https://www.6miu.com/read-1650346.html

最新回复(0)