题目:有 n 个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后最后留下的是原来第几号的那位。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013383042/article/details/77770764

题目:有 n 个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到 3 的人退出圈子,问最后最后留下的是原来第几号的那位。
提示:用数组完成

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;

public class DequeueNumThree {

    //数组
    public static void MethodArr(){
        System.out.println("Please input total people : ");
        Scanner scanner = new Scanner(System.in);
        int totalPeople = scanner.nextInt();

        boolean[] arr = new boolean[totalPeople];

        for(int i = 0; i < arr.length; i++){
            arr[i] = true;
        }

        int count = 0;//报数   1 2 3
        int leftPeople = totalPeople;//去掉报道3之后剩余的人数
        int index = 0;//数组下标
        while(leftPeople > 1){//最后只能剩余一个人
            if(arr[index] == true){//如果当前状态为true
                count++;//报数
                if(count == 3){//如果报数为3
                    arr[index] = false;//状态设置成false
                    count = 0;//为下次重新报数做准备
                    leftPeople--;//剩余人数减一
                }
            }

            index++;//到下一个人了

            if(index == totalPeople){//如果到最后一个人了,那么,从头重新开始报数
                index = 0;
            }
        }

        for(int i = 0; i < totalPeople; i++){
            if(arr[i] == true){
                System.out.println("last number is " + (i+1));
            }
        }
    }

    //容器
    public static void MethodCollection(){
        final int peoplesNum = 10;
        final int three = 3;

        List<Integer> peopleList = new ArrayList<Integer>();
        for(int i=0; i<peoplesNum; i++){
            peopleList.add(i+1);
        }
        System.out.println("total num of people : "+peopleList.size());

        int count = 1;
        ListIterator<Integer> iter = null;
        while(peopleList.size() > 1){
            iter = peopleList.listIterator();//循环一次,更新一次iter
            while(iter.hasNext()){
                int i = iter.next();
                System.out.println("now is " + i);
                if(count++ % three == 0){
                    iter.remove();
                    count = 1;
                    System.out.println(i+"------>out!");
                }
            }
        }

        System.out.println("\nlast people is "+peopleList);
    }

    public static void main(String[] args) {
        MethodArr();
//      MethodCollection();
    }
}

猜你喜欢

转载自blog.csdn.net/u013383042/article/details/77770764