一道Java算法题

13年前

100个人围成一个圈(编号0-99),从第0号的人开始从1报数,凡报到3的倍数的人离开圈子,然后再数下去,直到最后只剩一个人为止,问此人原来的位置是多少号?

 

源代码复制打印

  1. class Test   
  2. {   
  3.     public static void main(String[] args)   
  4.     {   
  5.         int count = 100;   
  6.         //剩余人数   
  7.         int leavings = count;   
  8.         int[] all = new int[count];   
  9.         //index人物编号,counter报数   
  10.         int index = 0, counter = 0;   
  11.         while (true)   
  12.         {   
  13.             //人物对应的值为-1表示出局   
  14.             if (all[index] != -1)   
  15.             {   
  16.                 all[index] = index+1;   
  17.                 counter++;   
  18.             }   
  19.             if (counter%3 == 0)   
  20.             {   
  21.                 if (--leavings == 1)   
  22.                 {   
  23.                     System.out.println(index);   
  24.                     break;   
  25.                 }   
  26.                 all[index] = -1;   
  27.             }   
  28.   
  29.             index++;   
  30.             if (index == count-1)   
  31.             {   
  32.                 index = 0;   
  33.             }   
  34.         }   
  35.     }   
  36. }