Chalkboard XOR Game in C++

C++Server Side ProgrammingProgramming

Suppose we have an array called nums, where nums[i] are written on a chalkboard. Ram and Sam take turns erasing exactly one element from the chalkboard, with Ram starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. Bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0. If any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player will win. Suppose the array is holding [1, 2, 1], so Ram can remove 1 or 2, if Ram removes 1, then the array will be [2,1], because XOR of elements 1 XOR 2 = 3, now Sam can remove any element, because Ram will be the one to erase the last element and he will lose., If he choses 2 to remove first, then the array becomes [1,1], XOR is 0, so Ram will lose.

To solve this, we will follow these steps −

  • n := size of nums
  • x := 0
  • for all elements i in nums −
    • x := x XOR i
  • return x is same as 0 or n mod 2 is 0

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool xorGame(vector<int>& nums) {
      int n = nums.size();
      int x = 0;
      for(int i : nums) x ^= i;
      return x == 0 || n % 2 == 0;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,1};
   cout << (ob.xorGame(v));
}

Input

{1,2,1}

Output

0
raja
Published on 02-Jun-2020 11:21:33
Advertisements