1009. Complement of Base 10 Integer
Every non-negative integer n
has a binary representation. For example, 5
can be represented as “101” in binary, and its complement is “010” which is the number 2
.
Given an integer n
, return its complement. The complement strategy is to flip the bits of its binary representation.
n = 5
2
5
is “101”, and its complement is “010” which is 2
in decimal.n = 1
0
1
is “1”, and its complement is “0” which is 0
in decimal.n
is in the range [0, 10^9]
.To solve the problem, the strategy involves the following steps:
bin()
function to get the binary representation of the integer.n
with all bits set to 1
.Here’s the Python code to achieve the solution:
def bitwiseComplement(n: int) -> int:
if n == 0:
return 1
# Calculate the bit length of n
bit_length = n.bit_length()
# Create a mask of the same bit length with all 1s
mask = (1 << bit_length) - 1
# XOR n with the mask to get the complement
return n ^ mask
n = 0
are handled (since the bitwise complement of 0 should be 1).[0, 10^9]
is respected, and the function is expected to handle large numbers efficiently.The time complexity of this solution is O(1) because:
Thus, the provided solution is efficient and works within the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?