[Algorithm-Mathematics] Nim Game

LeetCode(292) Nim Game
You and your friend, two people play [Nim] game together: There is a pile of rocks on the table, and each time you take turns to take 1-3 rocks. The one who removes the last stone is the winner. You act as the first mover. You are all smart people, and every step is the best solution. Write a function to determine whether you can win the game with a given number of stones.

Example:
Input: 4
Output: false
Explanation: If there are 4 stones in the pile, then you will never win the game; because whether you take 1, 2, or 3 stones, the last stone is always your friend Take away.

public class Nim {
    
    
	 /**
     * 因为只有最后剩余4块石头,那么作为先手一定不会赢,所以需要判断所给的石头数是否能被4整除,如果不能整除,则作为先手一定会赢
     * @param n 堆中石头的个数
     * @return
     */
    public static boolean canWinNim(int n) {
    
    
        return n % 4 != 0;
    }
}

Guess you like

Origin blog.csdn.net/runewbie/article/details/107052708
Recommended