LeetCode:Nim Game - 尼姆博弈

一、题目名称java

Nim Game(尼姆博弈)函数

二、题目地址code

https://leetcode.com/problems/nim-game/游戏

三、题目内容ip

英文:leetcode

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.rem

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.get

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.it

中文:io

你在和朋友玩“尼姆博弈”游戏,假设在桌上有一堆石子,二人轮流从这堆石子中拿走1到3块,取走最后一块石子的人获胜。这里假定你是第一个取石子的人。

假设你和你的对手都了解这个游戏的规则,写一个函数断定你是否能够取胜。

例如,若是有4块石头,那么你就是没法取胜的。不管你拿走一、二、3块石头,你的朋友均可以经过将其他的石子所有取走获胜。

四、解题方法1

网上已经有了不少对尼姆博弈问题的介绍,如维基百科页面:

https://en.wikipedia.org/wiki/Nim

解题Java代码以下:

/**
 * LeetCode 292 - Nim Game
 * @FileName Solution.java
 * @FileAuthor Tsybius
 * @DateTime 2015年12月20日 下午10:47:54
 */
public class Solution {
    
    /**
     * 计算尼姆博弈当前状况下是否必胜
     * @param n
     * @return
     */
    public boolean canWinNim(int n) {
        if (n <= 0) {
            return false;
        } else {
            return n % 4 != 0; 
        }
    }
}

另外一种解法是讨论区大牛给出的方法,采用位运算解决本问题。

/**
 * LeetCode 292 - Nim Game
 * @FileName Solution.java
 * @FileAuthor Tsybius
 * @DateTime 2015年12月20日 下午10:54:12
 */
public class Solution {
    
    /**
     * 计算尼姆博弈当前状况下是否必胜
     * @param n
     * @return
     */
    public boolean canWinNim(int n) {
        if (n <= 0) {
            return false;
        } else {
            return n >> 2 << 2 != n;
        }
    }
}

END

相关文章
相关标签/搜索