- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements