zoukankan      html  css  js  c++  java
  • 一圈同学(500)数数,数到三的同学退出,最后剩下的是哪位同学

    最近刚刚学习了java的数组,所以来一道题目练习一下。

    题目是:有500个同学围成一圈,从一个同学开始数数,数到3的同学退出,后面的同学重新从1开始数。请问最后是第几个同学剩下。

    代码如下:

     1 //用数组实现。
     2 public class Count3Quit {
     3     public static void main(String[] args){
     4         boolean[] Person = new boolean[500];
     5         
     6         //布尔数组中的所有元素的值都赋值为true
     7         for(int i = 0; i < Person.length; i++){
     8             Person[i] = true;
     9         }
    10         
    11         //当数组中元素的值为true代表元素还在队伍中
    12         //leftCount为剩余的元素数量
    13         //index为元素的下标
    14         //countNum为数的数目(1,2,3)
    15         int leftCount = Person.length;
    16         int countNum = 0;
    17         int index = 0;
    18         
    19         //当剩下的数目大于1的时候,将数到3的设置为false
    20         
    21         while(leftCount > 1){
    22             if(Person[index] == true){
    23                 countNum++;
    24                 
    25                 if(countNum == 3){
    26                     Person[index] = false;
    27                     countNum = 0;
    28                     leftCount--;
    29                 }
    30             }
    31             index++;
    32             
    33             if(index == Person.length){
    34                 index = 0;
    35             }
    36             
    37         }
    38         
    39         for(int i = 0; i < Person.length; i++){
    40             if(Person[i] == true)
    41                 System.out.print(i + " ");
    42         }
    43         
    44     }
    45 
    46 }

     最终结果如下:435 。这就是说明是第436个同学剩下。

  • 相关阅读:
    SlimDX.dll安装之后所在位置
    使用正则表达式进行简单查找
    UDP-C#代码
    非Unicode工程读取Unicode文件
    模板类重载<<运算符
    ganglia及ganglia-api相关介绍
    keystone v3 相关介绍
    ubuntu下ssh使用proxy:corkscrew
    neutron用linux_bridge部署provider网络
    python thread的join方法解释
  • 原文地址:https://www.cnblogs.com/fyymonica/p/2824747.html
Copyright © 2011-2022 走看看