加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[Swift]LeetCode1025. 除数博弈 | Divisor Game

发布时间:2020-12-14 04:53:51 所属栏目:百科 来源:网络整理
导读: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 . Replaci

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. 1 <= N <= 1000

爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。

最初,黑板上有一个数字?N?。在每个玩家的回合,玩家需要执行以下操作:

  • 选出任一?x,满足?0 < x < N?且?N % x == 0?。
  • 用?N - x?替换黑板上的数字?N?。

如果玩家无法执行这些操作,就会输掉游戏。

只有在爱丽丝在游戏中取得胜利时才返回?True,否则返回?false。假设两个玩家都以最佳状态参与游戏。

示例 1:

输入:2
输出:true
解释:爱丽丝选择 1,鲍勃无法进行操作。

示例 2:

输入:3
输出:false
解释:爱丽丝选择 1,鲍勃也选择 1,然后爱丽丝无法进行操作。

提示:

  1. 1 <= N <= 1000

Runtime:?4 ms
Memory Usage:?18.8 MB
1 class Solution {
2     func divisorGame(_ N: Int) -> Bool {
3         return N % 2 == 0        
4     }
5 }

Runtime:?4 ms

Memory Usage:?18.6 MB
 1 class Solution {
 2     func divisorGame(_ N: Int) -> Bool {
 3         var N = N
 4         var alice = false
 5         for x in 1..<N
 6         {
 7             alice.toggle()
 8             if N % x == 0
 9             {
10                 N -= x
11             }     
12         }
13         return alice
14     }
15 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读