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.
Hint:
- If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?
reference to this web:https://leetcode.com/discuss/64963/accepted-c-solution-with-explanation
explanation
well,the code is short and the important part is the idea behind the scene. according the example,if there are 4 stones,no matter what u do,u will lose. so as a smart guy u should leave 4 stone to yr friend. cos u can remove 3 stones at max, u'd win if there are 5~7 stones in the heap.
how about 8 stones in the heap? after removed,5~7 stones will be left.and yr smart friend will win by drive u into the 4 stones situation.
so u can win the game by counting the number of the stones, and make sure yr friend face the 4 stones situation.for example when n equal 15, u remove 3 stones,and 12 is 4 multiple 3.no matter how many stones yr friend removed, u can make it 8, and so on~~
BTW this is a boring game,u can win when the stones can not be divide by 4.
the C answer
bool canWinNim(int n) {
return n%4;
}