题目是:
17个人为成圈,依次编号为0-16,从第一号开始报数,报到3的倍数的人离开, 一直数下去,直到最后只剩1人,求此人的编号
我用java实现了一下,不知道还有没有更好的办法?
先建立一个Reader类
- public class Reader{
- private Integer person;
- private Integer num;
- public Integer getPerson() {
- return person;
- }
- public void setPerson(Integer person) {
- this.person = person;
- }
- public Integer getNum() {
- return num;
- }
- public void setNum(Integer num) {
- this.num = num;
- }
- }
下面才是主要代码
- import java.util.ArrayList;
- import java.util.List;
- public class TestNumber {
- /**
- * @param args
- */
- public static void main(String[] args) {
- List<Reader> list = new ArrayList<Reader>();
- for (int i = 1; i < 18; i++) {
- Reader reader=new Reader();
- reader.setPerson(i);
- reader.setNum(i);
- list.add(reader);
- }
- List dels = new ArrayList<Reader>();
- do {
- int j=list.size();
- int m = j;
- for (int i=0;i<j;i++) {
- Reader read = (Reader) list.get(i);
- if (read.getNum()%3==0) {
- dels.add(read);
- m=m-1;
- }
- read.setNum(read.getNum()+m);
- }
- list.removeAll(dels);
- dels.clear();
- } while (list.size()!=1);
- System.out.println(list.get(0).getPerson()+":"+list.get(0).getNum());
- }
- }
结果是11:50