Java-資料結構與演算法-逢3減1

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.