Given a positive integer num
, output its complement number. The complement strategy is to flip the bits of its binary representation.
num = 5
2
5
is 101
, and its complement is 010
which is the binary representation of 2
.num = 1
0
1
is 1
, and its complement is 0
.Q: What is the range of the input number num
?
A: The problem specifies that num
is a positive integer, typically within the range of a standard 32-bit integer in many problems.
Q: Are there any constraints on the performance of the solution? A: Given that this is an interview problem, we should aim for an efficient solution, ideally O(n) where n is the number of bits in the number.
def findComplement(num):
# Find binary representation of the number without the '0b' prefix
binary_rep = bin(num)[2:]
# Find the complement by flipping each bit
complement = ''.join('1' if bit == '0' else '0' for bit in binary_rep)
# Convert the complement back to an integer
return int(complement, 2)
# Test the function with the provided examples
print(findComplement(5)) # Output: 2
print(findComplement(1)) # Output: 0
bin(num)[2:]
: Converts the integer num
to a binary string and slices off the ‘0b’ prefix to get a clean binary representation.'1' if bit == '0' else '0' for bit in binary_rep
: A generator expression that flips each bit in the binary string.''.join(...)
: Joins the flipped bits back into a single string.int(complement, 2)
: Converts the binary string back to an integer.n
is the number of bits.Overall, the time complexity of the solution is O(n).
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?