Program to perform XOR operation in an array using Python


Suppose we have an integer n and another integer start. We have to create an array called nums where nums[i] = start + 2*i (i start from 0) and n is the size of nums. Then find the bitwise XOR of all elements of nums.

So, if the input is like n = 6, start = 2, then the output will be 14 because the array will be like [2+2*0, 2+2*1, ... 2+2*5] = [2,4,6,8,10,12], then XOR of each element present in the array is 14.

To solve this, we will follow these steps −

  • count := start

  • while n-1 > 0, do

    • count := count XOR 2 + start

    • n := n - 1

    • start := start + 2

  • return count

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(n, start):
   count = start
   while n-1 > 0:
      count ^= 2 + start
      n -= 1
      start += 2
   return count

n = 6
start = 2
print(solve(n, start))

Input

6, 2

Output

14

Updated on: 17-May-2021

595 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements