In this Leetcode Number Complement problem solution The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.

For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.

Given an integer num, return its complement.

Leetcode Number Complement problem solution


Problem solution in Python.

class Solution:
    def findComplement(self, num: int) -> int:
        b = bin(num)[2:]
        b = b.replace('1','2')
        b = b.replace('0', '1')
        b = b.replace('2','0')
        return int(b,2)

Problem solution in Java.

class Solution {
    public int findComplement(int num) {
        int r = 0;
        int i=1;
        while(num>i && i>0) {
            r += (num^i)&i;
            i = (i<<1);
        }
        return r;
    }
}

Problem solution in C++.

class Solution {
public:
    int findComplement(int num) {
        int res = 0;
        for(int shift = 0; num; ++shift, num >>= 1)
            res |= !(num & 1) << shift;
        return res;
    }
};

Problem solution in C.

int findComplement(int num){
        unsigned int msb  = ~0; int temp = num;
        while (temp){
                temp = temp >> 1;
                msb = msb << 1;
        }
        return (~num & ~msb);
}