Nim Game

题目链接:https://leetcode.com/submissions/detail/84164707/

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.

这个题目也比较简单,关键还是考察我们对数字观察的能力,题目已经告诉我们有4个石子的时候是啥情况了,意思就是你无论咋拿,收尾的肯定是对方,那么你就输了。

如果没石子的时候,应该返回false;
如果有1个石子,我全拿走,他玩儿完,返回true;
如果有2个石子,我全拿走,他玩儿完,返回true;
如果有3个石子,我全拿走,他玩儿完,返回true;
如果有4个石子,无论我怎么拿,都是人家收盘,返回false;
如果有5个石子,我拿走1个,对方无论怎么拿,他都得完蛋,返回true;
如果有6个石子,我拿走2个,对方无论怎么拿,他都得完蛋,返回true;
如果有7个石子,我拿走3个,对方无论怎么拿,他都得完蛋,返回true;
如果有8个石子,我无论怎么拿,他给我留4个(注意这一场景),我完蛋,返回false;
如果有9个石子,……

好了,写到这里差不多了,详细已经看出点门道了,如果谁最后接盘的是4个石子,那就完蛋。

下面是Java的代码实现:

public class NimGame {
    public boolean canWinNim(int n) {
        if (n == 0)
            return false;
        if (n <= 3)
            return true;
        if (n == 4)
            return false;

        return !(n % 4 == 0);
    }

    public static void main(String[] args) {
        NimGame nimGame = new NimGame();
        for (int i = 0; i < 100; i++) {
            System.out.println(i + ": "+ nimGame.canWinNim(i));
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值