返回介绍

solution / 0800-0899 / 0810.Chalkboard XOR Game / README_EN

发布于 2024-06-17 01:03:34 字数 3025 浏览 0 评论 0 收藏 0

810. Chalkboard XOR Game

中文文档

Description

You are given an array of integers nums represents the numbers 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. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.

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.

Return true _if and only if Alice wins the game, assuming both players play optimally_.

 

Example 1:

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 become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.

Example 2:

Input: nums = [0,1]
Output: true

Example 3:

Input: nums = [1,2,3]
Output: true

 

Constraints:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] < 216

Solutions

Solution 1

class Solution:
  def xorGame(self, nums: List[int]) -> bool:
    return len(nums) % 2 == 0 or reduce(xor, nums) == 0
class Solution {
  public boolean xorGame(int[] nums) {
    return nums.length % 2 == 0 || Arrays.stream(nums).reduce(0, (a, b) -> a ^ b) == 0;
  }
}
class Solution {
public:
  bool xorGame(vector<int>& nums) {
    if (nums.size() % 2 == 0) return true;
    int x = 0;
    for (int& v : nums) x ^= v;
    return x == 0;
  }
};
func xorGame(nums []int) bool {
  if len(nums)%2 == 0 {
    return true
  }
  x := 0
  for _, v := range nums {
    x ^= v
  }
  return x == 0
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文