[LeetCode] Chalkboard XOR Game

810. Chalkboard XOR Game

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.

1
2
3
4
5
6
7
8
class Solution {
public:
bool xorGame(vector<int>& nums) {
int res = 0;
for(auto& n : nums) res ^= n;
return !res or nums.size() % 2 == 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/27/PS/LeetCode/chalkboard-xor-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.