日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

Leet Code OJ 292. Nim Game [Difficulty: Easy]

發(fā)布時(shí)間:2024/2/28 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leet Code OJ 292. Nim Game [Difficulty: Easy] 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目:
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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。