以迴圈的解法為:
import java.util.Scanner;
import java.util.Scanner;public class Out3{public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [] people = new int[n];
int remain = n ; //還存活著的
int count = 0 ; //報數
int out = -1 ;//出局while (remain > 1) {
for (int i = 0; i < n; i++) {
if (people[i] != out) {
count++;
if (count == 3) {
count = 0;
remain--;
people[i] = out;
System.out.println("出局的是" + (i + 1));
}}
}
}
for(int i=0;i<n;i++)
{
if (people[i]!=out)
{
System.out.println("留下來的是"+(i+1)+"號");
}
}}}
以ArrayList的解法為
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;public class Num3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // 總共n 人
int count = 0;//数到该数的出局
List list = new ArrayList();
for (int i = 0; i < n; i++) {
list.add(i+1);
}while (list.size() > 1) {
for (int i = 0; i < list.size(); i++) {
count++;
if (count % 3 ==0) {
System.out.println(" " + list.get(i) + "号出局");
list.remove(i);
count = 0; // remove后后一个值取代了原来的值
i--;
}
}}System.out.println(list.get(0));}}}