LeetCode //C - 1025. Divisor Game

1025. 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 integer 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: n = 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.

Example 2:

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

Constraints:
  • 1 <= n <= 1000

From: LeetCode

Link: 1025. Divisor Game


Solution:

Ideas:

The result only depends on whether n is even or odd.

  • If n is even, Alice can always choose an odd divisor x, so n - x becomes odd for Bob.
  • If n is odd, every divisor x of n is also odd, so n - x becomes even for Bob.

So:

  • starting with an even number is a winning position
  • starting with an odd number is a losing position

Therefore, Alice wins iff n is even.

Code:
c 复制代码
bool divisorGame(int n) {
    return (n % 2 == 0);
}
相关推荐
涉密IT资质笔记1 分钟前
涉密资质投入产出分析模型:时间成本、四块成本构成与 ROI 决策框架
java·开发语言·算法
木井巳4 分钟前
【BFS 解决拓扑排序】火星词典
java·算法·leetcode·广度优先·宽度优先·图搜索算法
北风toto14 分钟前
KMP 算法详解:从暴力匹配到 O(n+m) 的字符串搜索
java·开发语言·算法
沫璃染墨16 分钟前
《从零入门数据结构与算法(二):线性表详解——从顺序表原理到静态与动态实现》
c语言·数据结构·顺序表
林澈在路上21 分钟前
哪个写歌软件可以用自己声音?MELO音乐详解
人工智能·python·算法
wuyk55522 分钟前
样章-第03讲-FreeRTOS在16KB-RAM上的裁剪与陷阱
c语言·开发语言·stm32·单片机·嵌入式硬件·物联网·系统架构
爱读书的小胖22 分钟前
Codewars Sum of a Sequence Hard Core Version C 解题分析
c语言·数据结构·算法
不会就选b22 分钟前
算法日常・每日刷题--<动态规划>24
算法·动态规划
夏虫不可与之言冰30 分钟前
使用Flash Download Tool给ESP32烧录固件
c语言·c++·windows·单片机·物联网·iot
Shaoshing34 分钟前
二分模板(左右查询)
java·算法·二分