1,2报数最后剩下的人的问题

         这是一个有趣的算法问题,1,2报数问50人最后留下的是哪个人?

         思路:这种报数分为两种形式一种围成一圈,另一种站成一排,前者每次都从头开始,后者首尾轮流报数

         第一种情况代码如下

public class TwoByDie {
	private static boolean c = true;
	private static int max = 10;
	private static int[] num;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		num = new int[max];
		for (int i = 0; i < max; i++) {
			num[i] = i + 1;
		}
		method(num, true);// 人,第一个是否为2,正序倒叙
	}

	private static void method(int[] nm, boolean is) {
		for (int x = 0; x < nm.length; x++) {
			System.out.print(nm[x] + " ");
		}

		int ss = nm.length;
		boolean iss = (ss % 2 == 0 ? true : false);
		int[] nmnm;
		if (ss % 2 == 0) {
			nmnm = new int[ss / 2];
		} else if (!is) {
			nmnm = new int[ss / 2];
		} else {
			nmnm = new int[ss / 2 + 1];
		}
//		if (((ss % 2 == 0) && is) || (ss % 2 == 1) && !is) {
//			nmnm = new int[ss / 2];
//		} else {
//			nmnm = new int[ss / 2 + 1];
//		}
		// [ss/2+ (ss%2==0&&is)?0:1];
		// System.out.println(nmnm.length+"  前集合nmnm");
		// c=!c;
		if (1 == ss) {
			System.out.println("最后一个人是:" + nm[0]);
		} else {
			// 正序
			System.out.println();
			for (int i = is ? 0 : 1, j = 0; i < ss; i += 2, j++) {
				nmnm[j] = nm[i];
			}
			// if(turn){
			// //第一个为1
			// if(is){
			// for(int i=0,j =0;i<ss;i+=2,j++){
			// nmnm[j] = nm[i];
			// }
			// }else{
			// //第一个为2
			// for(int i=1,j =0;i<ss;i+=2,j++){
			// nmnm[j] = nm[i];
			// }
			// }
			// }else{
			// // System.out.println(ss-1+"  后续集合  ");
			// // for(int x = 0 ;x<ss;x++){
			// // System.out.println(nm[x]+"  后zhi  ");
			// // }
			// if(is){
			// for(int i=ss-1,j=0;i>=0;i-=2,j++){
			// //System.out.println(j+"  后续集合  ");
			// nmnm[j] = nm[i];
			// }
			// }else{
			// //第一个为2
			// for(int i=ss-2,j=0;i>=0;i-=2,j++){
			// nmnm[j] = nm[i];
			// }
			// }
			// }
			method(nmnm, iss);// 人,第一个是否为2,正序倒叙
		}
	}
}
实现的方法很简单,只是为每次都新建的int数组附长度的时候想了一下

             其实第二种场景就在注解里,有空我再好好把方法归结下来!

             想这样的东西真的很好玩,此类文章未完待续!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值