一道Java算法題,居然做了很久......

灬猜想灬 14年前發布 | 4K 次閱讀 JavaScript Dropbox

有100個人圍成一個圈(編號0-99),從第0號的人開始從1報數,凡報到3的倍數的人離開圈子,然后再數下去,直到最后只剩一個人為止,問此人原來的位置是多少號?

public class Test
{
    public static void main(String[] args)
    {
        // count人物總數,index人物編號,counter報數
        int count = 100, index = 0, counter = 0;
        // 剩余人數
        int leavings = count;
        // 圈
        int[] circle = new int[count];
        System.out.println("人物編號    報數");
        while (true)
        {
            // 排的圈里的人物對應的值為-1表示出局
            if (circle[index] != -1)
            {
                circle[index] = index + 1;
                System.out.printf("%4d\t%3d\n", index, ++counter);
            }

            if (counter % 3 == 0 && circle[index] != -1)
            {
                if (leavings-- == 1)
                {
                    System.out.printf("最后一個:\n%4d\t%3d\n", index, counter);
                    break;
                }
                circle[index] = -1;
            }

            if (++index == count)
            {
                System.out.println("剩余人數:" + leavings);
                index = 0;
            }
        }
    }
}

 本文由用戶 灬猜想灬 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!