LeetCode-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塊。誰(shuí)拿到了最后一塊誰(shuí)贏。你先拿。兩個(gè)人都很聰明,都知道怎樣能贏。設(shè)計(jì)一個(gè)函數(shù)檢測(cè)對(duì)于給定的石子數(shù),你能否贏得比賽。

算法分析:

方法一:

如果最后剩下4個(gè)石子,后拿的那個(gè)人贏。因此如果是4的倍數(shù),你先拿x,后拿的人取4-x,因此后拿的那個(gè)人贏。

Java代碼
public class Solution {
    public boolean canWinNim(int n) {
        if (n % 4 == 0) return false;
        else return true;
    }
}
方法二

與方法一類(lèi)似,通過(guò)移位來(lái)判定是否是4的倍數(shù),不是,就能贏。

Java代碼
public class Solution {
    public boolean canWinNim(int n) {
        if (n <= 0) return false;
        
        return n>>2<<2 != n;
    }
}

參考

LeetCode
oschina
維基百科

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容