Swift算法9-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.

*** if there are 4 stones, you will never win!!! 大寫加粗!!!
所以你第一步走的話就可以先把石頭總數除以4的余數個數的石頭拿走,這樣剩余的石頭就是若干個4個石頭,對手先走的游戲了,于是你可以always win,但是如果石頭總數可以被4整除,那你就永遠不會贏。

class Solution {
    func canWinNim(n: Int) -> Bool {
       return n % 4 != 0 
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容