Given two integers, find XOR of them without using XOR operator, i.e., without using ^ in C/C++.
Input: x = 1, y = 2 Output: 3 Input: x = 3, y = 5 Output: 6
A Simple Solution is to traverse all bits one by one. For every pair of bits, check if both are same, set the corresponding bit as 0 in output, otherwise set as 1.
XOR is 6
Thanks to Utkarsh Trivedi for suggesting this solution.
A Better Solution can find XOR without using loop.
1) Find bitwise OR of x and y (Result has set bits where either x has set or y has set bit). OR of x = 3 (011) and y = 5 (101) is 7 (111)
2) To remove extra set bits find places where both x and y have set bits. The value of expression “~x | ~y” has 0 bits wherever x and y both have set bits.
3) bitwise AND of “(x | y)” and “~x | ~y” produces the required result.
Below is implementation.
XOR is 6
Thanks to jitu_the_best for suggesting this solution.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Find largest element from array without using conditional operator
- Check a number is odd or even without modulus operator
- Multiply a number with 10 without using multiplication operator
- Multiply any Number with 4 using Bitwise Operator
- Find a number which give minimum sum when XOR with every number of array of integers
- Find the Number Occurring Odd Number of Times
- Multiplication of two numbers with shift operator
- Compare two integers without using any Comparison operator
- Divide two integers without using multiplication, division and mod operator
- Multiplying a variable with a constant without using multiplication operator
- Find nth Magic Number
- Find a value whose XOR with given number is maximum
- Find the Missing Number
- Find whether a given number is a power of 4 or not
- Find Next Sparse Number