|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(1) |
| 3 | + |
| 4 | +# We are given non-negative integers nums[i] which are written on a chalkboard. |
| 5 | +# Alice and Bob take turns erasing exactly one number from the chalkboard, |
| 6 | +# with Alice starting first. If erasing a number causes the bitwise XOR of |
| 7 | +# all the elements of the chalkboard to become 0, then that player loses. |
| 8 | +# (Also, we'll say the bitwise XOR of one element is that element itself, |
| 9 | +# and the bitwise XOR of no elements is 0.) |
| 10 | +# |
| 11 | +# Also, if any player starts their turn with the bitwise XOR of all the elements |
| 12 | +# of the chalkboard equal to 0, then that player wins. |
| 13 | +# |
| 14 | +# Return True if and only if Alice wins the game, assuming both players play optimally. |
| 15 | +# |
| 16 | +# Example: |
| 17 | +# Input: nums = [1, 1, 2] |
| 18 | +# Output: false |
| 19 | +# Explanation: |
| 20 | +# Alice has two choices: erase 1 or erase 2. |
| 21 | +# If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of |
| 22 | +# all the elements of the chalkboard is 1 XOR 2 = 3. |
| 23 | +# Now Bob can remove any element he wants, because Alice will be the one |
| 24 | +# to erase the last element and she will lose. |
| 25 | +# If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of |
| 26 | +# all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. |
| 27 | +# |
| 28 | +# Notes: |
| 29 | +# - 1 <= N <= 1000. |
| 30 | +# - 0 <= nums[i] <= 2^16. |
| 31 | + |
| 32 | +from operator import xor |
| 33 | +from functools import reduce |
| 34 | + |
| 35 | + |
| 36 | +class Solution(object): |
| 37 | + def xorGame(self, nums): |
| 38 | + """ |
| 39 | + :type nums: List[int] |
| 40 | + :rtype: bool |
| 41 | + """ |
| 42 | + return reduce(xor, nums) == 0 or \ |
| 43 | + len(nums) % 2 == 0 |
0 commit comments