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

  • 相关阅读:
    周日讲课材料下载
    基础图论练习题
    邻接表存图的小trick(存多个图)
    0/1分数规划
    四道期望题
    基础线性代数大记(二)三道高消题
    基础线性代数大记 (一)前言与行列式的定义
    概率期望小记
    基础线性代数小记
    给二维数组排版
  • 原文地址:https://www.cnblogs.com/shamgod/p/4603963.html
Copyright © 2011-2022 走看看