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.)
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: 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
.
解题思路:
先求所有整数的异或值,如果为0,则alice赢。
如果不为0:
如果目前有偶数个数字,说明存在数,删掉后剩余整数的异或值不为0,问题转换为(Bob , 异或值不为0 , 奇数个) ;所以Bob输 , Alice赢 ;
如果目前有奇数个数
可能有奇数个完全相同的数字,删掉后剩余整数的异或值为0,Alice输;
存在不同的整数 , 删掉剩余的异或值不为0。问题转换为(Bob , 异或值不为0 , 偶数个) ;所以就会变成(Alice, 异或值不为0 , 奇数个)-》(Bob , 异或值不为0 , 偶数个) -》 (Alice , 异或值不为0 , 奇数个)......最后一个一定是Alice;Alice输 ;
其实我也想过判断奇偶数,就是没深入想下去,唉~
class Solution {
public:
bool xorGame(vector<int>& nums) {
int x = 0, n = nums.size();
for (int num : nums) x ^= num;
return x == 0 || n % 2 == 0 ;
}
};