Leetcode----292.Nim Game(easy)

本文分析了Nim游戏中的胜负策略。当石堆中有1至3颗石头时,先行者必胜;若石堆数量为4的倍数,则先行者必败。文章给出了Java和Python实现的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

经分析容易得到以下结论:
1、当石头的个数为1,或2,或3时,我必赢;
2、如果剩下石头的个数是4的倍数的话,那么谁先拿谁必输;
所以,当石头个数大于3的时候,如果初始值n不是4的倍数,那么我只要拿走一部分(1个或2个或3个)石头,使剩下的石头个数为4的倍数个,那么我必赢;如果初始值n是4的倍数,那么我必输;
数学表达:

 



java版1:
public class Solution {
	public boolean canWinNim(int n) {
		if (n > 3 && n % 4 == 0) {
			return false;
		} else {
			return true;
		}
	}
}

java版2:
public class Solution {
	public boolean canWinNim(int n) {
	return  n % 4 != 0? true:false;
	}
}








python版:
class Solution(object):
    def canWinNim(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n % 4 > 0



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值