Complement of Base 10 Integer (LeetCode 1009): Solution and Explanation

Easy
Bit Manipulation

Flip every bit of n from bit 0 up to its highest 1 and return the number that results, with n = 0 giving 1.

Intuition

A bitwise NOT flips all 32 bits, including the zeros above the highest 1 of n. Those become 1s and the answer turns into a negative number, so NOT alone is wrong.

The bits that should flip are exactly the ones n still has while you keep shifting it right. Read the lowest bit with n & 1, write its opposite at the same position of the answer, then shift n right. When n hits 0 there are no significant bits left, so the loop stops before it can touch a leading zero.

The only input the loop never enters is n = 0. Its binary form is the single digit 0, and the complement of that is 1.

Approach: Read the low bit, write it flipped

  1. If n == 0, return 1.
  2. Set result = 0 and bit = 0.
  3. While n > 0: if n & 1 is 0, set bit bit of result with result |= 1 << bit.
  4. Shift n right by one and add one to bit.
  5. Return result.

Step-by-step example

n = 5
  1. 5 is 101 in binary. result = 0, bit = 0.
  2. Lowest bit of 101 is 1, so bit 0 of result stays 0. Shift: n = 10, bit = 1.
  3. Lowest bit of 10 is 0, so set bit 1: result = 10 (2). Shift: n = 1, bit = 2.
  4. Lowest bit of 1 is 1, so bit 2 stays 0. Shift: n = 0, bit = 3.
  5. n is 0, so stop. Return 2.

Code: Python, Java, C++

1class Solution:
2    def bitwiseComplement(self, n: int) -> int:
3        if n == 0:
4            return 1
5        result = 0
6        bit = 0
7        while n > 0:
8            if n & 1 == 0:
9                result |= 1 << bit
10            n >>= 1
11            bit += 1
12        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Bit length formula O(1)
Read the low bit, write it flipped O(log n)
All-ones mask plus XOR O(log n)
Time

O(log n)

The loop runs once per bit of n, and n has about log2(n) bits.

Space

O(1)

Only result and the bit counter are stored.

Other approaches

All-ones mask plus XOR (time O(log n), space O(1))

Grow mask = 1, 11, 111, ... until mask >= n, then return n ^ mask. Starting the mask at 1 also gives the right answer for n = 0, since 0 ^ 1 = 1.

Bit length formula (time O(1), space O(1))

Compute the bit length L of n (at least 1) and return ((1 << L) - 1) - n. Subtracting from an all-ones number is the same as flipping each bit.

Common mistakes

  • Returning ~n. It flips the leading zeros as well and gives a negative number.
  • Forgetting n = 0. The loop never runs, so it returns 0 instead of 1.
  • Writing the flipped bit at the wrong position. The bit read from n after k shifts belongs at position k of the answer, so keep a separate counter instead of shifting the result.

Frequently asked questions

Why does the loop never flip a leading zero?

Each pass shifts n right by one. After the highest 1 has been read and shifted out, n is 0 and the loop ends, so positions above the highest 1 are never visited.

How is this different from LeetCode 476, Number Complement?

It is the same task except that 1009 allows n = 0. Code written for 476 that starts a mask at 1 already returns 1 for zero, but a bit-reading loop needs the explicit check.

Can result overflow?

No. n is below 10^9, which fits in 30 bits, and the answer never has more bits than n.