Number Complement
Easy
Topics
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
~n would also flip the leading zeros and give a negative result. Masking with 7 keeps it to 2.Input: n = 5 Output: 2 Explanation: 101 -> 010.
Example 2
Input: n = 1 Output: 0
Example 3
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
- Walk
nright one bit at a time, shiftingmaskleft each step, untilnis exhausted. - 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 2Complexity
- 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, and0 ^ 0is 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) ^ nimport java.util.*;
class Solution {
public int findComplement(int n) {
int mask = 1, t = n;
while (t > 0) {
mask <<= 1;
t >>= 1;
}
return (mask - 1) ^ n;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int findComplement(int n) {
int mask = 1, t = n;
while (t > 0) {
mask <<= 1;
t >>= 1;
}
return (mask - 1) ^ n;
}
};/**
* @param {number} n
* @return {number}
*/ var findComplement = function(n) {
let mask = 1, t = n;
while (t > 0) {
mask <<= 1;
t >>= 1;
}
return (mask - 1) ^ n;
};