VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-xor-of-two-number-without-using-xor-operator/

⇱ Find XOR of two number without using XOR operator - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find XOR of two number without using XOR operator

Last Updated : 17 Mar, 2025

Given two integers, the task is to find XOR of them without using the XOR operator.

Examples :

Input: x = 1, y = 2
Output: 3

Input: x = 3, y = 5
Output: 6

Approach - Checking each bit - O(log n) time and O(1) space

A Simple Solution is to traverse all bits one by one. For every pair of bits, check if both are the same, set the corresponding bit like 0 in output, otherwise set it as 1. 


Output
3

Using AND, OR & NOT Operators - O(1) time and O(1) space

Approach 1:

The idea is to use a combination of OR, AND, and NOT operations to simulate XOR functionality. Since XOR sets a bit when only one of the corresponding bits in the input numbers is set (but not both), we can achieve this by first finding all positions where either bit is set using OR, and then removing positions where both bits are set using a logical trick with complements.

This works through Boolean algebra manipulation. The expression (x | y) & (~x | ~y) can be understood in two parts: (x | y) identifies all bit positions where at least one of x or y has a set bit, while (~x | ~y) is the complement of (x & y) (by De Morgan's law), meaning it has 0 bits only where both x and y have set bits. When we AND these two expressions together, we get 1 only in positions where either x or y (but not both) has a set bit - which is exactly the definition of XOR.


Output
3

Approach 2:

The idea is to use one of the properties of the XOR bitwise operator i.e. a + b = a^b + 2*(a & b), with the help of this we can do the same for an operator variant also.


Output
3

Approach 3:

The idea is to subtract the AND(&) of the two numbers from the OR(|) so that the common bit gets canceled and the opposite bits remain in the answer.


Output
3
Comment
Article Tags: