LeetCode 292 Nim Game(Nim游戏)

翻译

你正在和你的朋友们玩下面这个Nim游戏:桌子上有一堆石头,每次你从中去掉1-3个。谁消除掉最后一个石头即为赢家。你在取出石头的第一轮。

你们中的每一个人都有着聪明的头脑和绝佳的策略。写一个函数来确定对于给定的数字是否你可以赢得这场比赛。

例如,如果堆中有4个石头,那么你永远也无法赢得比赛:无论你移除了1、2或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.

分析

题目一开始不是很理解,因为朋友如果有2个、3个、多个的情况是完全不一样的呐,后来仔细一看原文第一句 withyourfriend ,发现只是和1个朋友玩游戏。

于是我设定了一个判断条件

bool yourTrun = true;

后面巴拉巴拉写了一堆代码全错……

加上一天的劳累我开始趴着睡觉了,脑子里还在回想。忽然发现:

1-true
2-true
3-true
4-false
5-true
6-true
7-true
8-false

然后抬起头重新写了一遍:

bool canWinNim(int n) {
    if ((n - 1) % 4 == 0 || (n - 2) % 4 == 0 || (n - 3) % 4== 0) return true;       
    else return false;             
}

哇,通过了,感觉整理整理:

bool canWinNim(int n) {
    return (n - 1) % 4 == 0 || (n - 2) % 4 == 0 || (n - 3) % 4 == 0;
}

继续整理,原来这么简单呐:

bool canWinNim(int n) {
    return n % 4 != 0;
}

忽然就不困了。^_^

代码

class Solution {
public:      
    bool canWinNim(int n) {
        return n % 4 != 0;
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值