Magicsheet logo

Number Complement

Easy
100%
Updated 6/1/2025

Number Complement

What is this problem about?

The Number Complement problem asks you to flip every bit of a positive integer's binary representation and return the result. For example, the complement of 5 (binary: 101) is 010 = 2. Crucially, you only flip the bits that are "active" in the number's binary length — not leading zeros. This Number Complement coding problem tests targeted bit manipulation.

Why is this asked in interviews?

Microsoft, Meta, Google, and J.P. Morgan ask this easy problem to test bit manipulation fundamentals — specifically computing a bitmask of the exact length of the input's binary representation. The bit manipulation interview pattern is the core, and the ability to compute the mask dynamically distinguishes clean solutions from hacky ones.

Algorithmic pattern used

Bitmask of the same length. Compute the number of bits in num: bits = num.bit_length(). Create a mask of that many 1s: mask = (1 << bits) - 1. Return num XOR mask. XOR with all 1s flips every bit within the number's active range.

Example explanation

num=5 (binary: 101). bit_length=3. mask = (1<<3)-1 = 7 (binary: 111). 5 XOR 7 = 101 XOR 111 = 010 = 2.

num=1 (binary: 1). bit_length=1. mask=1. 1 XOR 1 = 0.

num=6 (binary: 110). bit_length=3. mask=7. 6 XOR 7 = 110 XOR 111 = 001 = 1.

Common mistakes candidates make

  • XOR-ing with all 1s (0xFFFFFFFF) — flips leading zeros too, giving wrong result.
  • Not computing the correct bit length (using a fixed 32-bit mask).
  • Off-by-one in the mask computation: (1 << bits) - 1 not (1 << (bits-1)) - 1.
  • Using string reversal as a workaround (correct but slower and less elegant).

Interview preparation tip

Bit complement problems require masking to the exact bit length of the number. The formula (1 << bit_length) - 1 creates a mask of bit_length ones. This masking technique is reusable across many bit manipulation problems: extracting the lower k bits, clearing the upper bits, flipping exactly k bits. Practice computing masks for arbitrary bit lengths — it's a fundamental bit manipulation building block.

Similar Questions