你正在和你的朋友們玩下面這個Nim游戲:桌子上有一堆石頭,每次你從中去掉1-3個。誰消除掉最後一個石頭即為贏家。你在取出石頭的第一輪。
你們中的每一個人都有著聰明的頭腦和絕佳的策略。寫一個函數來確定對於給定的數字是否你可以贏得這場比賽。
例如,如果堆中有4個石頭,那麼你永遠也無法贏得比賽:無論你移除了1、2或3個石頭,最後一個石頭都會被你的朋友所移除。
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個、3個、多個的情況是完全不一樣的吶,後來仔細一看原文第一句
於是我設定了一個判斷條件
bool yourTrun = true;
後面巴拉巴拉寫了一堆代碼全錯……
加上一天的勞累我開始趴著睡覺了,腦子裡還在回想。忽然發現:
1-true
2-true
3-true
4-false
5-true
6-true
7-true
8-false
然後抬起頭重新寫了一遍:
bool canWinNim(int n) {
if ((n - 1) % 4 == 0 || (n - 2) % 4 == 0 || (n - 3) % 4== 0) return true;
else return false;
}
哇,通過了,感覺整理整理:
bool canWinNim(int n) {
return (n - 1) % 4 == 0 || (n - 2) % 4 == 0 || (n - 3) % 4 == 0;
}
繼續整理,原來這麼簡單吶:
bool canWinNim(int n) {
return n % 4 != 0;
}
忽然就不困了。^_^
class Solution {
public:
bool canWinNim(int n) {
return n % 4 != 0;
}
};