Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.
class Solution {
    public int findComplement(int num) {
        if(num == 0)
            return 1;

        int rightFirstOneMinusOne = 32;
        for(int i = 31; i >= 0; i--) {
            if(((num >> i) & 1) == 1) {
                rightFirstOneMinusOne = i;
                break;
            }
        }

        for(int i = rightFirstOneMinusOne; i >= 0; i--) {
            num = num ^ (1 << i);
        }

        return num;
    }
}

results matching ""

    No results matching ""