介绍
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.
思路
扔石头游戏,每次扔1到3个石头,我先扔,扔掉最后一个石头的人赢,写个函数根据石头数目确定自己能否赢。显然可以通过递归来做。
终止条件:n<4,赢,n=4,输
。。。这样一看都用不着递归,直接看除以4的余数是多少就行了,如果除以4的余数是0,那么肯定输,因为不管你扔多少个,后扔的肯定补到4,最后剩4个就输了
那么如果除以4的余数不是0呢?肯定赢,因为只要第一轮扔出余数,后扔者不管扔什么你跟着补到4,最后肯定是赢
so easy
代码
|
|