zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    python中元类(metaclass)的理解
    aiohttp
    async/await
    asyncio
    协程
    Bayesian Non-Exhaustive Classification A case study:online name disambiguation using temporal record streams
    技术网址
    网站
    各种网址
    OpenGL学习网址2
  • 原文地址:https://www.cnblogs.com/shamgod/p/4603963.html
Copyright © 2011-2022 走看看