292. Nim Game | 抓石子游戏

来源:互联网 发布:金融数据挖掘工程师 编辑:程序博客网 时间:2024/05/01 03:18

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.


思路:通过分析可以看出n=1,2,3成功,n=4失败,后面的n,如果在n-1,n-2,n-3中的一个数中是失败的,则n是成功的,进一步查看规律则可看出,如果n可以整除4,则n失败,否则成功,那么代码就很简单了.

public boolean canWinNim(int n) {if (n%4==0) {return false;}else return true;}


0 0
原创粉丝点击