Java-数据结构与算法-逢3减1
生活随笔
收集整理的這篇文章主要介紹了
Java-数据结构与算法-逢3减1
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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退1 23 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--; //剩余人數要減1 34 } 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
?
轉載于:https://www.cnblogs.com/shamgod/p/4603963.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Java-数据结构与算法-逢3减1的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3月任务--target
- 下一篇: 大型Javascript应用架构的模式(