Nim Game

Problem: Nim Game

It's easy to understand for number of stones less than 4, you'll definitely win. And for number equals 4, you'll lose. But for number like 5, 6, 7, you can easily make it 4 stones left for your rival then he'll lose. For 8 you'll leave surely-win situations like 5, 6, 7 to your rival. From this, we can know these situations happen repeatedly as multiples of 4. You can also return the answer in bit-manipulation way.

Code in Python:

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

results matching ""

    No results matching ""