LeetCode:Nim Game - 尼姆博弈

部署运行你感兴趣的模型镜像

1、题目名称

Nim Game(尼姆博弈)

2、题目地址

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

3、题目内容

英文:

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块,取走最后一块石子的人获胜。这里假定你是第一个取石子的人。

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

例如,如果有4块石头,那么你就是无法取胜的。无论你拿走1、2、3块石头,你的朋友都可以通过将其余的石子全部取走获胜。

4、解题方法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

转载于:https://my.oschina.net/Tsybius2014/blog/548232

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值