You were playing the following Nim Game with your friend:there was a heap of stones on the table and each time one of your take Turns to remove 1 to 3 stones. The one who removes, the last stone would be the winner. You'll take the first turn to remove the stones.
Both of you is very clever and has optimal strategies for the game. Write a function to determine whether your can win the game given the number of stones in the heap.
For example, if there is 4 stones in the heap and then you'll never win the Game:no matter 1, 2, or 3 stones you remove, The last stone is always being removed by your friend.
This rule is the first to smoke, then it is very simple to first look at the law:
1:win
2:win
3:win
4: Can't win anyway
5: Take 1 and let the other face 4
6: Take 2 and let the other face 4
7: Take 3 and let the other face 4
8: No Way
.....
Visible, when the number of stones is a multiple of 4, the initiator is helpless, so the code is very simple, as follows:
1 class Solution {2public:3 bool canwinnim (int n) {4 return n%4; 5 }6 };
Leetcode Oj:nim Game (Nim games)