algoadvance

Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.

Example 1:

Example 2:

Clarifying Questions

  1. 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.

  2. 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.

Strategy

  1. Convert the number to binary: First, get the binary representation of the number.
  2. Calculate the complement: Flip each bit in the binary string to get the complement.
  3. Convert back to integer: Convert the resulting binary string back into an integer.

Code

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

Explanation

  1. bin(num)[2:]: Converts the integer num to a binary string and slices off the ‘0b’ prefix to get a clean binary representation.
  2. '1' if bit == '0' else '0' for bit in binary_rep: A generator expression that flips each bit in the binary string.
  3. ''.join(...): Joins the flipped bits back into a single string.
  4. int(complement, 2): Converts the binary string back to an integer.

Time Complexity

Overall, the time complexity of the solution is O(n).

Try our interview co-pilot at AlgoAdvance.com