现在有100个人犯人,每个人的编号是1,2,...100.国王准备赦免一个人,赦免的规则:先干掉奇数位置的人。 剩下的人从新保留队列,继续干掉奇数位置的人。直到最终剩下一个人为止,此人即是幸运者,请算出他的编号。
eg.1 2 3 4 5 6 7 8 9
2 4 6 8
4 8
8
分析步骤:
a、定义一个数组存储100个人的编号。
b、定义一个死循环,去掉奇数位置的人。
c、把非奇数位置的人的编号从新存入到新的数组中去。
d、新数组重复上述过程,直到剩下一个人为止即是幸运者。
(1)第一种解法:
package com.szh.lianxi; import java.util.Arrays; public class xinyunzhe1 { public static void main(String[] args) { //定义一个数组存储100个人的编号。 int[] people=new int[100]; for (int i = 0; i < 100; i++) { people[i]=i+1; } System.out.println("数组元素为:" + Arrays.toString(people)); //把非奇数位置的人的编号从新存入到新的数组中去。 while(true){ int[] peoplenew=new int[people.length/2]; int index=0; for(int i=1;i<people.length;i+=2){ peoplenew[index++]=people[i]; } System.out.println("本轮幸存者:"+Arrays.toString(peoplenew)); if(peoplenew.length==1){ break; } //新数组重复上述过程,直到剩下一个人为止即是幸运者。 people=peoplenew; } } }
(2)第二种写法:
package com.szh.lianxi; import sun.font.TrueTypeFont; import java.util.Scanner; public class xinyunzhe2 { public static int h=1; public static int sum=0; public static void main(String[] args) { Scanner sc=new Scanner(System.in); while(true) { System.out.println("请输入一共有多少个犯人:"); int n=sc.nextInt(); while(n>1) { for(int i=1;h<=n;i++) { h=2*h; } n=n/2;//人数减少一半,奇数的人被杀了 sum=h/2; } System.out.println("幸运者的编号是"+sum); } } }