有100个人围成一个圈,从1开始报数,报到14的这个人就要退出

来源:互联网 发布:linux如何嗅探欺骗 编辑:程序博客网 时间:2024/05/16 07:53
package com.itheima;import java.util.ArrayList;import java.util.List;/* * 10、 有100个人围成一个圈,从1开始报数,报到14的这个人就要退出。然后其他人重新开始,从1报数,到14退出。问:最后剩下的是100人中的第几个人? */public class Test10 {public static void main(String[] args) {Circle c = new Circle();c.exits2();}}class Circle{private List<Integer> queue = new ArrayList<Integer>();  //队列private int maxIndex = 0;  //最大索引值private int currentIndex = 0; //当前索引值//第一种方法public void exit(){//生成队列for(int i=1; i<=100; i++){queue.add(i);}maxIndex = queue.size() - 1;while(queue.size() > 1){for(int j=1; j<=14; j++){//如果当前索引大于了最大索引,说明已经数到最后一个号,重新数if(currentIndex > maxIndex){currentIndex = 0;}System.out.println("第" + queue.get(currentIndex) + "号,数" + j);if(j==14){System.out.println("第" + queue.remove(currentIndex) + "号退出");   //去除当前索引的值,将队列的后面的值都提前一个索引System.out.println("当前存在的号为:" + queue);maxIndex--;        //最大索引减一,currentIndex当前索引不变,即将队列后面一个号,作为当前的索引值}else{currentIndex++;   //每循环一次,当前的索引就会加一,跳到队列中的下个数}}}}//第二种方法public void exits2(){boolean[] queue = new boolean[100];for(int i=0;i<queue.length;i++){queue[i] = true;}int len = queue.length;int count = 0;while(len>1){for(int i=0;i<queue.length;i++){if(queue[i]==true){count++;if(count == 14){queue[i] = false;count=0;len--;}}}}for(int i=0;i<queue.length;i++){System.out.println(i + " : " + queue[i]);}}}

0 0
原创粉丝点击