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

本文通过两种方法解决了经典的报数游戏问题:一种是使用数组记录每个人的状态,另一种是利用List容器进行迭代删除。最终找到最后一个留在圈中的人的编号。

题目:有 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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值