[Swift]LeetCode810. 黑板异或游戏 | Chalkboard XOR Game

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-dxwmghyc-me.html 
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

We are given non-negative integers nums[i] which are written on a chalkboard.  Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first.  If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses.  (Also, we'll say the bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.)git

Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.github

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

Example:
Input: nums = [1, 1, 2]
Output: false
Explanation: 
Alice has two choices: erase 1 or erase 2. 
If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. 
If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.

Notes:微信

  • 1 <= N <= 1000
  • 0 <= nums[i] <= 2^16.

一个黑板上写着一个非负整数数组 nums[i] 。小红和小明轮流从黑板上擦掉一个数字,小红先手。若是擦除一个数字后,剩余的全部数字按位异或运算得出的结果等于 0 的话,当前玩家游戏失败。 (另外,若是只剩一个数字,按位异或运算获得它自己;若是无数字剩余,按位异或运算结果为 0。)spa

换种说法就是,轮到某个玩家时,若是当前黑板上全部数字按位异或运算结果等于 0,这个玩家获胜。code

假设两个玩家每步都使用最优解,当且仅当小红获胜时返回 true。htm

示例:
输入: nums = [1, 1, 2]
输出: false
解释: 
小红有两个选择: 擦掉数字 1 或 2。
若是擦掉 1, 数组变成 [1, 2]。剩余数字按位异或获得 1 XOR 2 = 3。那么小明能够擦掉任意数字,由于小红会成为擦掉最后一个数字的人,她老是会输。
若是小红擦掉 2,那么数组变成[1, 1]。剩余数字按位异或获得 1 XOR 1 = 0。小红仍然会输掉游戏。

说明:blog

  • 0 <= N <= 1000
  • 0 <= nums[i] <= 2^16

Runtime: 68 ms
Memory Usage: 18.7 MB
 1 class Solution {
 2     func xorGame(_ nums: [Int]) -> Bool {
 3         var x:Int = 0
 4         var n:Int = nums.count
 5         for num in nums
 6         {
 7             x ^= num
 8         }
 9         return x == 0 || n % 2 == 0
10     }
11 }

68ms游戏

1 class Solution {
2     func xorGame(_ nums: [Int]) -> Bool {
3         return nums.count % 2 == 0 || nums.reduce(0, ^) == 0
4     }
5 }
相关文章
相关标签/搜索