[Leetcode] Nim Game

来源:互联网 发布:先知者软件 编辑:程序博客网 时间:2024/05/21 10:16

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.

Hint:

  1. If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

你跟你朋友玩一个游戏:桌上有一堆石头,你们俩轮流拿走石头(每次可以拿走1个2个或者3个),拿走最后一个石头的人获胜。游戏从你开始。

例如,如果这一堆有四个石头,那你永远不可能获胜,因为无论你先拿走1个两个或者是3个,最后一个石头永远都是被你朋友拿走。


思路:

最终剩下4个石头,谁先拿谁就输了。

所以如果石头数量为4n,那你就永远赢不了,因为不论你怎么取,你朋友都能够在你拿走x个之后拿走4-x个来保证最后只剩4个石头时由你开始;

如果石头数量为4n+i (i=1,2,3),你可以通过第一次拿走i个的方式将4n开始的人转移到你朋友,从而赢得比赛。

所以本题关键就在于判断石头个数是不是4的倍数,若是,则你输,若不是,则你赢。


Python 代码:

方法1:

class Solution(object):    def canWinNim(self, n):        """        :type n: int        :rtype: bool        """        return bool(n%4)

方法2:

class Solution(object):    def canWinNim(self, n):        """        :type n: int        :rtype: bool        """        return bool(n&3)

方法2是通过按位与运算来判断n是否为4的倍数,因为3的二进制表示为00...0011, 若n为4的倍数,则n的二进制表示最后两位数字应该为00,这样与运算结果就全为0,则bool结果为False;若n不为4的倍数,则其二进制表示最后两位数中至少有一位是1,那么与运算结果就不可能为0,所以bool结果为True。

0 0
原创粉丝点击