payal-kothari
7/13/2017 - 4:54 PM

Find complement of binary number. It won't work if you give negative integer. Remember the two steps.

Find complement of binary number.

It won't work if you give negative integer. Remember the two steps.


public class Solution {
    public int findComplement(int num) {
          
        int hb = Integer.highestOneBit(num) -1;  
        num = ~num;       // bitwise negation
        
        return num & hb;  // bitwise &
    }
}