1025. Divisor Game*

1025. Divisor Game*

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

题目描述

Alice and Bob take turns playing a game, with Alice starting first.

Initially, there is a number N on the chalkboard. On each player’s turn, that player makes a move consisting of:

  • Choosing any x with 0 < x < N and N % x == 0.
  • Replacing the number N on the chalkboard with N - x.

Also, if a player cannot make a move, they lose the game.

Return True if and only if Alice wins the game, assuming both players play optimally.

Example 1:

Input: 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.

Example 2:

Input: 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.

Note:

  • 1 <= N <= 1000

C++ 实现 1

这是逻辑思维题… 参考 just return N % 2 == 0 (proof) 解决. 其中有个评论解释的相当精彩:
https://leetcode.com/problems/divisor-game/discuss/274566/just-return-N-2-0-(proof)/262708

引用如下:

My reasoning is like this. Whoever loses for k will win for k+1, because he/she can choose 1 and the opponent will face the situation of k. The key point is that Alice loses if Bob wins, and Bob loses if Alice wins. As we know, Alice loses when the number is 1, therefore, when it is 2, Alice wins (because Alice loses when it is 1) and Bob loses. When the number is 3, Bob wins (because Bob loses when it is 2) and Alice loses. So on and so forth. We can conclude that Alice wins and Bob loses when k is even; Bob wins and Alice loses when k is odd.

所以代码很简洁:

class Solution {
public:
    bool divisorGame(int N) {
        return N % 2 == 0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值