哈哈,再分享道有意思的题目,代码其实很简单,主要是想明白~
定义一个盒子类,有一个属性,三个方法:
public class Box{
Boolean flag = false;
public Box(){
}
public void open(){
flag=true;
}
public void close(){
flag=false;
}
public void reverse(){
flag=!(flag);
}
}
再定义个Test类:
public class TestBox {
public static void main(String[] args) {
final int total =1000;
Box[] b = new Box[total];
for (int i =0;i<total;i++){
b[i]=new Box();
}
//the first person
for (int i =0;i<total;i++) {
b[i].open();
}
//the second person
for (int i = 1; i < total; i = i + 2) {
b[i].close();
}
//the third person and the last
for (int a = 3; a <= total; a++) {
for (int i = a-1; i < total; i = i + a) {
b[i].reverse();
}
}
int count=0;
for (int i =0;i<total;i++){
if (b[i].flag==true){
count++;
}
}
System.out.println(count);
}
}