KatInterview

476. Number Complement

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the "complement" of a given positive integer num. The complement is defined by flipping all the 0s to 1s and 1s to 0s in its binary representation. A key detail is that this flipping operation applies only to the significant bits of the number. For example, the integer 5 is 101 in binary. We are interested in its 3-bit representation, not its 32-bit representation which would have many leading zeros. Flipping the bits of 101 gives 010, which is the integer 2.

Solution

Number Complement in Python

class Solution:
    def findComplement(self, num: int) -> int:
        # The complement of a number is found by flipping its bits.
        # This is equivalent to XORing the number with a mask of all 1s
        # that has the same bit length as the number.
        # e.g., for num = 5 (101), the mask is 7 (111). 5 ^ 7 = 2 (010).
        
        # In Python, we can easily find the number of bits in num's binary representation.
        # e.g., num = 5 (101), num.bit_length() is 3.
        # e.g., num = 8 (1000), num.bit_length() is 4.
        bit_length = num.bit_length()
        
        # Create a mask with `bit_length` ones.
        # This can be done with (1 << bit_length) - 1.
        # e.g., bit_length = 3 -> (1 << 3) - 1 = 8 - 1 = 7 (111).
        mask = (1 << bit_length) - 1
        
        # The complement is num XORed with the mask.
        return num ^ mask

Number Complement in Java

class Solution {
    public int findComplement(int num) {
        // We need a mask with the same bit length as num, but with all bits set to 1.
        // For example, if num is 5 (binary 101), the mask should be 7 (binary 111).
        // The complement is then num ^ mask.
        // A concise way to create this mask is to find the smallest power of 2 that is
        // strictly greater than num. Let's call it p. Then the mask is p - 1.
        
        // We use a long for the mask to avoid overflow, as num can be up to 2^31 - 1.
        // If num is 2^31 - 1, the mask would need to become 2^31, which overflows a signed int.
        long mask = 1;
        while (mask <= num) {
            mask <<= 1;
        }
        
        // After the loop, `mask` is the smallest power of 2 strictly greater than `num`.
        // `mask - 1` gives us a bitmask of all 1s with the correct length.
        // The result is (mask - 1) XOR num.
        return (int)((mask - 1) ^ num);
    }
}

Number Complement in C++

class Solution {
public:
    int findComplement(int num) {
        // We need a mask that has 1s for all significant bits of num.
        // For num = 5 (101), mask should be 7 (111).
        // The complement is then num ^ mask.
        // A concise way to build this mask is to find the smallest power of 2
        // that is strictly greater than num, and then subtract 1.
        
        // We use 'long long' for the mask to prevent overflow when num is large.
        // If num is 2^31 - 1, the smallest power of 2 greater than it is 2^31,
        // which would overflow a 32-bit signed int.
        long long mask = 1;
        while (mask <= num) {
            mask <<= 1;
        }

        // After the loop, `mask` is the smallest power of 2 strictly greater than `num`.
        // `mask - 1` gives us a bitmask of all 1s with the correct length.
        return (mask - 1) ^ num;
    }
};

Number Complement in TypeScript

function findComplement(num: number): number {
    // We need a mask that has 1s for all significant bits of num.
    // For num = 5 (101), mask should be 7 (111).
    // The complement is then num ^ mask.
    // We can build the mask by finding the smallest power of 2 >= num,
    // and then creating an all-ones mask from there.

    let mask = 1;
    while (mask < num) {
        // Keep adding a bit to the left until the mask is large enough
        // to cover all bits of num.
        mask = (mask << 1) | 1;
    }

    // The complement is the XOR of num and the mask.
    return num ^ mask;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.