Bit Manipulation Solutions
Bit Manipulation Solutions
[email protected]
Solution 1: The value of x^x = 0.
Think about it, xor gives 0 when the bits are the same. If we compare the same number to
itself, the bits will always be the same. So, the answer of x^x will always be 0.
Solution 2: The idea is to use XOR operators to swap two numbers by their property
x^x=0
public class Solution {
public static void main(String[] args) {
int x = 3, y = 4;
System.out.println("Before swap: x = " + x + " and y = " + y);
//swap using xor
x = x ^ y;
y = x ^ y;
x = x ^ y;
System.out.println("After swap: x = " + x + " and y = " + y);
}
}
Solution 3 : The expression -~x will add 1 to an integer x. We know that to get negative of
a number, invert its bits and add 1 to it (Remember negative numbers are stored in 2’s
complement form), i.e.,
-x = ~x + 1;
-~x = x + 1 (by replacing x by ~x)