能否用面向对象的方法实现
猴子选大王 n个猴子围成一圈,从第一个猴子开始重复一二三,数到三的猴子从圈子中出来,最后剩下的一个猴子就是大王。编程模拟。此过程,输出猴子出圈的编号次序和大王的编号。 搜索更多相关的解决方案:
面向对象
----------------解决方案--------------------------------------------------------
程序代码:
import java.util.*;
class Monkey {
static int number = 0;
private int no;
public Monkey() {
number++;
this.no = number;
}
public String toString() {
return "Monkey" + no;
}
}
public class MonkeyKing {
public LinkedList<Monkey> list = new LinkedList<Monkey>();
public MonkeyKing(int n) {
for (int i=0; i<n; i++) {
list.add(new Monkey());
}
}
public void selectKing() {
list = parseList(list,3);
System.out.println("The monkey king is " + list.get(1));
}
public static LinkedList parseList(LinkedList list,int pos) {
while(list.size()>pos-1){
for (int i = 0; i < pos-1; i++) {
list.addLast(list.getFirst());
list.remove(i);
}
list.removeFirst();
System.out.println(list);
}
return list;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
MonkeyKing mk = new MonkeyKing(n);
mk.selectKing();
}
}
class Monkey {
static int number = 0;
private int no;
public Monkey() {
number++;
this.no = number;
}
public String toString() {
return "Monkey" + no;
}
}
public class MonkeyKing {
public LinkedList<Monkey> list = new LinkedList<Monkey>();
public MonkeyKing(int n) {
for (int i=0; i<n; i++) {
list.add(new Monkey());
}
}
public void selectKing() {
list = parseList(list,3);
System.out.println("The monkey king is " + list.get(1));
}
public static LinkedList parseList(LinkedList list,int pos) {
while(list.size()>pos-1){
for (int i = 0; i < pos-1; i++) {
list.addLast(list.getFirst());
list.remove(i);
}
list.removeFirst();
System.out.println(list);
}
return list;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
MonkeyKing mk = new MonkeyKing(n);
mk.selectKing();
}
}
----------------解决方案--------------------------------------------------------
谢谢 我去研究研究
public class Main {
public static void main(String[] args) {
int[] a=new int[500];
for (int i=0;i<500;i++){
a[i]=1;
}
int b=0;
int i=0;
int sum=0;
do{
b=0;
sum=sum+a[i];
if(sum==3) {
sum=0;a[i]=0;
}
i=i+1;
if(i==500){
i=0;
for(int j=0;j<500;j++){
b=b+a[j];
}
}
}while(b!=1);
for(i=0;i<500;i++){
if(a[i]==1){
System.out.println(i);
}
}
}
}
只会普通 这个好像能用链表的把
----------------解决方案--------------------------------------------------------