標籤:
1.要求:有一群人圍成一圈數數,逢3退1人,要求算出最後留下來的人的下標
2.代碼:
1 package Test; 2 3 public class Count3Quit1 { 4 5 //要求:有一群人圍成一圈數數,逢3退1人,要求算出最後留下來的人的下標 6 7 public static void main(String[] args) { 8 9 //接收java 參數指定人數10 int len = Integer.parseInt(args[0]);11 12 //用boolean數組數組類比一圈人,true表示還在,false表示已退出13 boolean [] peoples = new boolean[len]; 14 /*for(boolean b : peoples){15 b = true;16 }*/17 for(int i = 0; i < peoples.length; i++){18 peoples[i] = true;19 }20 21 22 //逢3退123 int leftCount = len; //1.leftCount表示目前剩多少人24 int index = 0; //2.index當前的元素下標25 int count = 0; //3.count表示數到多少26 27 while(leftCount > 1){28 if(peoples[index]){29 count++;30 if(count == 3){31 peoples[index] = false;32 count=0;33 leftCount--; //剩餘人數要減134 }35 }36 37 //把元素下標下稱38 index++;39 40 //如果已數到數組盡頭則重頭開始數41 if(index > len-1){42 index = 0;43 }44 }45 46 for(int i = 0; i < peoples.length; i++){47 if(peoples[i]){48 System.out.println(i);49 }50 }51 }52 }
3.運行結果 java Count3Quit1 500:
435
Java-資料結構與演算法-逢3減1