Easy 2-line mathematical solution without language specific manipulation (JAVA)

  • 0

    The idea is that we need to find out how many bits are needed to fit a number in a base 2 system. We, therefore take log2(num) which tells us how many times we need to divide the number by 2 to get 1 as the answer. This by extension helps us find how many bits are required.

    public int findComplement(int num) {
                int ceil = (int) (Math.log(num)/Math.log(2));
                return ~num & (1 << ceil) - 1;

    For e.g. 10 is represented as 1010, log2(10) gives us 3, hence we require at max -> 2^3 (4) bits
    Next, we reduce 2^3 by 1 to get a mask of 111. This is done because no matter what the input is, the leftmost bit will be 0.
    Simple negation and ANDING the number gives us the answer

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.