-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path810-ChalkboardXORGame.go
More file actions
62 lines (52 loc) · 2.34 KB
/
810-ChalkboardXORGame.go
File metadata and controls
62 lines (52 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
// 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.
// 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] < 2^16
import "fmt"
func xorGame(nums []int) bool {
xor, n := 0, len(nums)
for i := 0; i < n; i++ {
xor ^= nums[i]
}
if xor == 0 { return true }
if n % 2 == 0 { return true }
return false
}
func main() {
// 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.
fmt.Println(xorGame([]int{1,1,2})) // false
// Example 2:
// Input: nums = [0,1]
// Output: true
fmt.Println(xorGame([]int{0,1})) // true
// Example 3:
// Input: nums = [1,2,3]
// Output: true
fmt.Println(xorGame([]int{1,2,3})) // true
}