3號出局

YH Lin
3 min readFeb 5, 2020

--

有n個人圍成一圈,順序排號(從1號編到 n 號)。從第一個人開始報數(從1到3報數),凡報到3的人出局退出圈子,問最後留下的是第幾號。

以迴圈的解法為:

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));}}}

--

--