XOR operator

What is XOR operator?

The XOR operator (^) is a bitwise operator that performs the exclusive OR operation on its operands.

The exclusive OR operation is a logical operation that returns true (1) if exactly one of its operands is 1. It return false (0) if both operands are 0 or both operands are 1.

XOR operator example

0 ^ 0 = 1

XOR operator truth table

xyx ^ y
000
011
101
110

Useful properties XOR operator:

argument XOR 0 = argument

x ^ 0 = x

argument XOR argument = 0

x ^ x = 0

Commutativity

x ^ y = y ^ x

Programming problem related XOR operator:

In-Place Swapping: Swap two values x and y in-place, i.e. without using any helper variables.

let x = 10, y = 5;
 
// 'x' binary (1010) and 'y' binary (0101)
x = x ^ y; // x now becomes 15 (1111)
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)
Finding the Missing Number: You are given an array A of n – 1 integers which are in the range between 1 and n. All numbers appear exactly once, except one number, which is missing. Find this missing number.
Finding the Duplicate Number: You are given an array A of n + 1 integers which are in the range between 1 and n. All numbers appear exactly once, except one number, which is duplicated. Find this duplicated number.
Finding Two Missing/Duplicate Numbers: You are given an array A of n – 2 integers which are in the range between 1 and n. All numbers appear exactly once, except two numbers, which are missing. Find these two missing numbers.
Reference: