500个小朋友手拉手围成一个圈,依次按123报数,报到3的出列,最后一个留在圈里的是第几个?
Posted yxfyg
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了500个小朋友手拉手围成一个圈,依次按123报数,报到3的出列,最后一个留在圈里的是第几个?相关的知识,希望对你有一定的参考价值。
public class Count3Quit{ //从数组的角度 public void m1(){ boolean[] child = new boolean[500]; for(int i=0;i<child.length;i++){ child[i] = true; } int count = 0; int left = child.length; int index = 0; while(left > 1){ if(child[index]){ count++; } if(count == 3){ child[index] = false; left--; count = 0; } index++; if(index == 500){ index = 0; } } for(int i=0;i<child.length;i++){ if(child[i]){ System.out.println(i); } } } //从类的角度 public void m2(){ Circle circle = new Circle(500); Child d = circle.first; int num = 0; while(circle.count > 1){ num++; if(num == 3){ circle.delete(d); num = 0; } d = d.right; } System.out.println(circle.first.index); } public static void main(String[] args){ Count3Quit c = new Count3Quit(); c.m1(); c.m2(); } } class Circle{ int count = 0; Child first,end; public Circle(int num){ for(int i=0;i<num;i++){ add(); } } void add(){ Child c = new Child(count); if(count == 0){ c.left = c; c.right = c; first = c; end = c; } else{ c.left = end; end.right = c; end = c; c.right = first; first.left = c; } count++; } void delete(Child c){ if(count == 0){ System.out.println("空空如也"); return; } else if(count == 1){ first = end = null; } else{ c.left.right = c.right; c.right.left = c.left; if(c == first){ first = c.right; } else if(c == end){ end = c.left; } } count --; } } class Child{ int index; Child left; Child right; public Child(int index){ this.index = index; } }
以上是关于500个小朋友手拉手围成一个圈,依次按123报数,报到3的出列,最后一个留在圈里的是第几个?的主要内容,如果未能解决你的问题,请参考以下文章