Monkey King (Java)

Monkey King (Java)


Question requirements: To complete the game of selecting the king of monkeys, it is required to enter the number of monkeys and the value of the number reported. The monkeys reporting the specified value in the order of arrangement are out. The last remaining is the king, and the number of the king is output.

import java.util.Scanner;

public class MonkeyChooseKing {
    
    
	public static void main(String[] arge) {
    
    
		int king=0;
		System.out.print("请输入猴子的数量:");
		Scanner sc=new Scanner(System.in);
		int num=sc.nextInt();
		int a[]=new int[num];
		
		for(int i=0;i<num;i++) {
    
    
			a[i]=1;
		}
		
		int n=a.length;
		int j=0;
		
		while(n>1) {
    
    //循环 直到队伍中只剩一只猴子
			for(int i=0;i<num;i++) {
    
    
				if(a[i]!=0)
					j++;//报数
				if(j%3==0&&a[i]!=0) {
    
    //是三的倍数且未出队
					a[i]=0;//出队
					n--;//队伍中猴子数减一
				}
			}
		}
		for(int i=0;i<num;i++) {
    
    
			if(a[i]!=0)
				king=i+1;//未出队猴子即为大王
		}
		System.out.print("大王的猴子的编号为:"+king);
	}
}

operation result:

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_47335800/article/details/109271253