leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 03ca5c6054084ae3997c481efbc6e8eeb31a005c
parent 47a601b11c9e02232e12ac7f90b04ea7a1a259bd
Author: Jack Sangdahl <jack@pngu.org>
Date:   Wed, 12 Nov 2025 22:23:09 -0700

810. chalkboard xor game

Diffstat:
Achalkboard_xor_game.c | 28++++++++++++++++++++++++++++
Achalkboard_xor_game.py | 32++++++++++++++++++++++++++++++++
2 files changed, 60 insertions(+), 0 deletions(-)

diff --git a/chalkboard_xor_game.c b/chalkboard_xor_game.c @@ -0,0 +1,28 @@ +// 810. Chalkboard XOR Game +#include "leetcode.h" + +/* + * you are given an array of integers 'nums' that represents the numbers written + * on a chalboard. alice and bob take turns erasing exactly one number from the + * chalboard, with alice starting first. if erasing a number causes the bitwise + * xor of all the elements of the chalboard to become 0, then the 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. + */ + +bool xorGame(int *nums, int numsSize) { + int x = 0; + for (int i = 0; i < numsSize; i++) + x ^= nums[i]; + return !x || !(numsSize % 2); +} + +int main() { + int n1[] = {1, 1, 2}, n2[] = {0, 1}, n3[] = {1, 2, 3}; + printf("%d\n", xorGame(n1, ARRAY_SIZE(n1))); // expect: 0 + printf("%d\n", xorGame(n2, ARRAY_SIZE(n2))); // expect: 1 + printf("%d\n", xorGame(n3, ARRAY_SIZE(n3))); // expect: 1 +} diff --git a/chalkboard_xor_game.py b/chalkboard_xor_game.py @@ -0,0 +1,32 @@ +# 810. Chalkboard XOR Game + +""" +you are given an array of integers 'nums' that represents the numbers written +on a chalboard. alice and bob take turns erasing exactly one number from the +chalboard, with alice starting first. if erasing a number causes the bitwise +xor of all the elements of the chalboard to become 0, then the 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. +""" + + +class Solution(object): + def xorGame(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + x = 0 + for i in nums: + x ^= i + return x == 0 or len(nums) % 2 == 0 + + +if __name__ == "__main__": + obj = Solution() + print(obj.xorGame(nums=[1, 1, 2])) + print(obj.xorGame(nums=[0, 1])) + print(obj.xorGame(nums=[1, 2, 3]))