Question
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.
Answer
When the number of pebbles for the first time, the initiator can take away, the initiator win;
When the stone number is 4 o'clock, regardless of the 1, 2, or 3, the hand to win;
When the number of stones is 5, the initiator first take one, the face of the stone with a number of 4 of the situation, the initiator win;
......
Therefore, when the number of stones is a multiple of 4, the flip-win, otherwise the initiator wins.
The strategy of winning is: the number of stones taken each time, and the number of stones taken from the previous tempo added to 4.
The winning strategy is: each time the number of stones to be taken, the number of remaining stones is a multiple of 4.
class Solution {public: bool canwinnim (int n) { if (n%4= =0) returnfalse; Else return true ; }};
292. Nim Game