Number Complement

Easy

Topics
Bit Manipulation

The complement of an integer is the number you get by flipping all the bits in its binary representation (within its bit-length). Given a positive integer n, return its complement.

Example 1

210n = 5101answer010
Every bit flips, but only within the number’s own 3-bit width — a plain ~n would also flip the leading zeros and give a negative result. Masking with 7 keeps it to 2.
Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input:  n = 5
Output: 2
Explanation: 101 -> 010.

Example 2

0n = 11answer0
Input:  n = 1
Output: 0

Example 3

210n = 7111answer000
Input:  n = 7
Output: 0

Constraints

  • 1 <= n < 2^31
Editorial — intuition, approach, complexity and pitfalls

Intuition

The complement flips every bit within the number's own bit length. A plain bitwise NOT flips all 32 or 64 bits, which turns a small positive into a negative — so the flip has to be masked to the significant bits.

Build a mask of all 1s exactly as wide as n. Shifting a single bit left once per bit of n gives a power of two just above it; subtracting 1 turns that into a solid run of 1s. XOR with that mask flips precisely the bits that belong to n and leaves the rest alone.

n    = 101  (5)
mask = 111  (7)
XOR  = 010  (2)

💡 XOR with 1 flips a bit, XOR with 0 leaves it; so XOR against a mask is "flip exactly where the mask is set".

Approach

  1. Walk n right one bit at a time, shifting mask left each step, until n is exhausted.
  2. Return (mask - 1) ^ n.

Dry Run

n = 5 (101)

mask=1  t=5    -> mask=2   t=2
mask=2  t=2    -> mask=4   t=1
mask=4  t=1    -> mask=8   t=0
loop ends

mask - 1 = 7 = 111
7 ^ 5 = 111 ^ 101 = 010 = 2

answer 2

Complexity

  • Time — O(log n): one iteration per bit.
  • Space — O(1).

Common Pitfalls

  • Returning ~n. That flips the high bits too and gives a negative result.
  • Building the mask from a fixed 32 bits. That flips leading zeros which are not part of the number, so 5 would come back as 4294967290 rather than 2.
  • Off-by-one on the mask: it must be 2^bits - 1, so the loop shifts once per bit and then subtracts 1.
  • Not handling n = 0, where the loop never runs, the mask stays 1, and 0 ^ 0 is 0 — correct here only because the constraints start at 1, so check what your language does before relying on it.

Full Solution — all languages

class Solution:
    def findComplement(self, n):
        mask = 1
        t = n
        while t > 0:
            mask <<= 1
            t >>= 1
        return (mask - 1) ^ n
SensAI
Beta
Tap the mic to stop voice mode