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.
For example, The integer 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 < 10^9
Can you implement a function to find the complement of a given integer? Consider edge cases and aim for an efficient solution.
The problem asks us to find the complement of a given integer. The complement is obtained by flipping all the bits (0s to 1s and 1s to 0s) in the binary representation of the integer.
def find_complement_naive(n):
binary_string = bin(n)[2:]
flipped_string = ''.join(['1' if bit == '0' else '0' for bit in binary_string])
return int(flipped_string, 2)
A more efficient approach involves bit manipulation. The idea is to create a mask with the same number of bits as the input integer n
, but with all bits set to 1. Then, we can XOR the input integer with the mask to flip all the bits.
n
in binary.n
with the mask to get the complement.def find_complement_optimal(n):
if n == 0: # Edge case. 0's complement is 0.
return 0
num_bits = 0
temp = n
while temp > 0:
num_bits += 1
temp >>= 1
mask = (1 << num_bits) - 1
return n ^ mask
The optimal approach using bit manipulation is more efficient in terms of space complexity compared to the naive approach that involves string conversions. Both solutions have a time complexity of O(log n), but the bit manipulation approach avoids the overhead of string manipulation, making it slightly faster in practice.