62,614
社区成员
发帖
与我相关
我的任务
分享
static int GetNum(int n)
{
Queue<int> queue = new Queue<int>();
for (int i = 1; i <= n; ++i) queue.Enqueue(i);
int num = 1;
while (queue.Count > 1)
{
if (num++ % 3 == 0) queue.Dequeue();
else queue.Enqueue(queue.Dequeue());
}
return queue.Dequeue();
}
public class Kids {
private static final int LENGTH = 500;
public static void main(String[] args) {
int[] array = new int[LENGTH];
for (int i = 0; i < array.length; i++) {
array[i] = i + 1;
}
int n = 0;
int i = 0;
while (getSize(array) > 1) {
if (array[i] > 0) {
n++;
}
if ((n % 3) == 0) {
array[i] = -1;
}
if (i < LENGTH - 1) {
i++;
} else {
i = 0;
}
}
for (int k : array) {
if (k > 0) {
System.out.println("the number of the last kid is:" + i);
}
}
}
public static int getSize(int[] array) {
int n = 0;
for (int i : array) {
if (i > 0) {
n++;
}
}
return n;
}
}
结果是268.
package com.zf.test;
import java.util.LinkedList;
import java.util.List;
public class Test3 {
//虚拟 n 个children
public List<Integer> buildChildren(int childrenSize){
List<Integer> children = new LinkedList<Integer>();
for (int i = 1 ; i <= childrenSize; i++) {
children.add(i);
}
return children;
}
//递归计算
public int calc (int currentNo , int currentListIndex , List<Integer> children){
if(currentListIndex == children.size()){
if(children.size() > 1){
currentListIndex = 0 ;
}else{
return children.get(0);
}
}
if(currentNo == 3){
children.remove(currentListIndex);
currentNo = 1;
}else{
currentNo++;
currentListIndex++;
}
return calc(currentNo , currentListIndex , children) ;
}
//包装
public int run( int childrenSize){
return calc(1 , 0 , buildChildren(childrenSize));
}
public static void main(String[] args) {
Test3 t = new Test3();
System.out.println("最后退出的小朋友为:" + t.run(500));
}
}