292_Nim Game

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.

  判断哪位玩家能赢,只要某个玩家在抓石子的时候,保证抓之前所有石子数量是4的整数倍即可。

  因为每个玩家一次能抓1-3个,如果石子总数可以被4整除,不管先手抓几个,后手若保证一轮拿走总石子数为4,这样先手永远不能赢。比如4个,先手拿1-3个,后手一定能赢;若是5个,先手拿一个,保证剩余石子个数可以被4整除,那么后手永远不能赢;若是6个,先手拿2个,剩余4个,后手拿1-3个,一定输…………

class Solution {
public:
  bool canWinNim(int n) {
    if(n % 4 == 0)
    {
      return false;
    }
    else
    { 
      return true;
    }
  }
};
原文地址:https://www.cnblogs.com/Anthony-Wang/p/4997523.html