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.
经分析容易得到以下结论:
1、当石头的个数为1,或2,或3时,我必赢;
2、如果剩下石头的个数是4的倍数的话,那么谁先拿谁必输;
所以,当石头个数大于3的时候,如果初始值n不是4的倍数,那么我只要拿走一部分(1个或2个或3个)石头,使剩下的石头个数为4的倍数个,那么我必赢;如果初始值n是4的倍数,那么我必输;
数学表达:
java版1:
public class Solution {
public boolean canWinNim(int n) {
if (n > 3 && n % 4 == 0) {
return false;
} else {
return true;
}
}
}
public class Solution {
public boolean canWinNim(int n) {
return n % 4 != 0? true:false;
}
}
python版:
class Solution(object):
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n % 4 > 0