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