Leet Code OJ 292. Nim Game [Difficulty: Easy]
題目:
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.
分析:
題意是2個人玩游戲,桌上有一堆石頭,一次只能拿1到3個石頭,誰把最后的石頭拿走,誰就是贏家。現在,你是第一次拿石頭的人。寫程序來判斷,給定石頭數n,你是否可以必贏。
簡單來說,撇去第一次拿的石頭,無論對方拿幾個,你都要有應對的數量。對方出1時,2人組合出的數量是2~4;對方出2時,組合出的數量是3~5;對方出3時,數量是4~6。也就是4這個數字是無論對方出什么,都可以組合出來的。故,我們將每4個石頭作為一組。假設總數是4的倍數,那無論你每次拿什么,對方都可以跟你組成4,最終的石頭一定是對方拿的;反之,如果不是4的倍數,你只要把除以4的余數,在第一次拿走,從第二次開始,無論對方出什么,都組成4,你就必贏了。
代碼實現1:
public class Solution {public boolean canWinNim(int n) {if(n%4==0){return false;}else{return true;}} }代碼實現2:
public class Solution {public boolean canWinNim(int n) {int nk=n&3;return nk != 0;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 292. Nim Game [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 136. Si
- 下一篇: Leet Code OJ 242. Va