The complement of an integer is the integer you get when you flip all the 0
's to 1
's and all the 1
's to 0
's in its binary representation.
5
is "101"
in binary and its complement is "010"
which is the integer 2
.Given an integer n
, return its complement.
Example 1:
Input: n = 5 Output: 2 Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Example 2:
Input: n = 7 Output: 0 Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
Example 3:
Input: n = 10 Output: 5 Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
Constraints:
0 <= n < 109
Note: This question is the same as 476: https://leetcode.com/problems/number-complement/
The problem asks to find the complement of a given integer n
. The complement is obtained by flipping all the bits in the binary representation of the number (0s become 1s and 1s become 0s). The solution uses bit manipulation for efficient computation.
The core idea is to iterate through the bits of the input number n
and generate the complement bit by bit. Here's a breakdown:
Handle the base case: If n
is 0, its complement is 1. This is a special case we handle upfront.
Iterative bit manipulation: We use a while
loop to process the bits of n
. Inside the loop:
(n & 1)
extracts the least significant bit (LSB) of n
.(n & 1 ^ 1)
XORs the LSB with 1, effectively flipping the bit (0 becomes 1, 1 becomes 0).<< i
left-shifts the flipped bit by i
positions, placing it in its correct position in the result ans
.n >>= 1
right-shifts n
by 1, discarding the processed LSB and moving to the next bit.i += 1
increments the shift counter i
.Return the complement: After the loop completes, ans
holds the binary representation of the complement, which is then returned.
class Solution:
def bitwiseComplement(self, n: int) -> int:
if n == 0:
return 1
ans = i = 0
while n:
ans |= ((n & 1 ^ 1) << i) # Flip bit and place it in ans
i += 1
n >>= 1 # Move to next bit
return ans
The Python code directly implements the steps outlined above. The other languages (Java, C++, Go, TypeScript, Rust) follow a very similar structure, adapting the syntax to their respective languages.
n
. The number of bits is proportional to log₂(n).ans
, i
, n
).Let's trace the execution for n = 5
:
n
is not 0, so the base case is skipped.n & 1
is 1, n & 1 ^ 1
is 0, 0 << 0
is 0, ans
remains 0, n
becomes 2.n & 1
is 0, n & 1 ^ 1
is 1, 1 << 1
is 2, ans
becomes 2, n
becomes 1.n & 1
is 1, n & 1 ^ 1
is 0, 0 << 2
is 0, ans
remains 2, n
becomes 0.ans
, which is 2 (the complement of 5).This example demonstrates how the algorithm efficiently computes the bitwise complement.