Now we’ve flipped all the bits but it also flipped previously insignificant bits (0s), so to revert them back to 0s, we need to only keep the significant bits and turn off the insignificant bits
This can be done by using mask of 1s having size equal to number of bits in num. This mask is (1 « nBits) - 1
This is a standard mask in bit manipulation problems
To find complement of num = 5 which is 101 in binary.
First ~num gives ...11111010 but we only care about the rightmost 3 bits.
Then to erase the 1s before 010 we can add 1000
publicclassSolution {
publicintfindComplement(int num) {
// Find the number of bits in the given numberint bitLength = Integer.toBinaryString(num).length();
// Create a mask with all bits set to 1 of the same length as the binary// representation of numint mask = (1 << bitLength) - 1;
// XOR num with the mask to flip all bitsreturn num ^ mask;
}
}