LeetCode Algorithum
# | title | solution | difficulty |
292 | Nim Name | java | easy |
NO.292
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.
你和你的朋友Nim一起玩游戏:桌子上有一堆石头,你们轮流取出1~3个石头谁是取出最后一个石头的为赢家,从你开始。
你们非常聪明,各自都有对应的方案,写一个函数来确保开始时石头的数量针对你是必赢的。
比如:如果这堆石头有4个,那么你将永远不会获胜:不管是取出1个,2个或3个,最后的石头都会是你的朋友取出的。
Hint: 如果这堆石头有5个,你就可以想出一个方法,将总是你获胜
- 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?
public class Solution {
public boolean canWinNim(int n) {
if(n % 4 == 0) {
return false;
} else {
return true;
}
}
}