本文主要是介绍题目:有 n 个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后最后留下的是原来第几号的那位。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:有 n 个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到 3 的人退出圈子,问最后最后留下的是原来第几号的那位。
提示:用数组完成
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;public class DequeueNumThree {//数组public static void MethodArr(){System.out.println("Please input total people : ");Scanner scanner = new Scanner(System.in);int totalPeople = scanner.nextInt();boolean[] arr = new boolean[totalPeople];for(int i = 0; i < arr.length; i++){arr[i] = true;}int count = 0;//报数 1 2 3int leftPeople = totalPeople;//去掉报道3之后剩余的人数int index = 0;//数组下标while(leftPeople > 1){//最后只能剩余一个人if(arr[index] == true){//如果当前状态为truecount++;//报数if(count == 3){//如果报数为3arr[index] = false;//状态设置成falsecount = 0;//为下次重新报数做准备leftPeople--;//剩余人数减一}}index++;//到下一个人了if(index == totalPeople){//如果到最后一个人了,那么,从头重新开始报数index = 0;}}for(int i = 0; i < totalPeople; i++){if(arr[i] == true){System.out.println("last number is " + (i+1));}}}//容器public static void MethodCollection(){final int peoplesNum = 10;final int three = 3;List<Integer> peopleList = new ArrayList<Integer>();for(int i=0; i<peoplesNum; i++){peopleList.add(i+1);}System.out.println("total num of people : "+peopleList.size());int count = 1;ListIterator<Integer> iter = null;while(peopleList.size() > 1){iter = peopleList.listIterator();//循环一次,更新一次iterwhile(iter.hasNext()){int i = iter.next();System.out.println("now is " + i);if(count++ % three == 0){iter.remove();count = 1;System.out.println(i+"------>out!");}}}System.out.println("\nlast people is "+peopleList);}public static void main(String[] args) {MethodArr();
// MethodCollection();}
}
这篇关于题目:有 n 个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后最后留下的是原来第几号的那位。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!