Nim Game

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

拿石子的游戏。假设有一堆石子,没人每次可以拿1个,两个,最多三个。如果是你先拿,让你判断你是否会赢。假设玩游戏的人都很聪明,知道怎样回赢。题目中的提示假设石子有四颗,无论我们拿几颗我们都会输,对方肯定能一次拿走剩余的石子。如果是八颗石子也是一样的。事实上石子的个数为4的倍数我们肯定就会输。代码很简单,判断是否为4的倍数,代码如下:
public class Solution {
    public boolean canWinNim(int n) {
        return n % 4 == 0 ? false : true;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2279215