1. 程式人生 > >292. Nim Game (取物遊戲) by Python

292. Nim Game (取物遊戲) by Python

number true object following 個數 ima def 就會 obj

292. 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~3個,你先拿,給你石頭的數量問你能不能贏

答案:

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

一道腦筋急轉彎,想通了會變得很簡單,就是如果石頭是四的倍數的時候誰先拿x個,另一個就可以拿4-x個,這樣到最後剩下4個的時候先拿的就會輸掉,
所以只要自己先拿,讓石頭個數變為4的倍數,就可以讓對方輸掉,所以只要驗證個數是不是4的倍數就可以了。

292. Nim Game (取物遊戲) by Python