Given two strings representing two complex numbers, you need to return a string representing their product. The complex numbers are in the form “a+bi” where a
and b
are integers, and i
is the imaginary unit.
a
and b
?
a
and b
are integers.To solve this problem, you can follow these steps:
Here’s an implementation in Python:
def complexNumberMultiply(num1: str, num2: str) -> str:
# Helper function to parse the complex number
def parse_complex(num):
real, imaginary = num.split('+')
return int(real), int(imaginary[:-1]) # remove 'i' at the end
# Parse the complex numbers
a, b = parse_complex(num1)
c, d = parse_complex(num2)
# Perform complex number multiplication
real_part = a * c - b * d
imag_part = a * d + b * c
# Format the result back to the "a+bi" form
return f"{real_part}+{imag_part}i"
# Example usage:
num1 = "1+1i"
num2 = "1+1i"
print(complexNumberMultiply(num1, num2)) # Output: "0+2i"
parse_complex
splits the input string by ‘+’, converts the real part directly to an integer, and the imaginary part after removing the trailing ‘i’.The time complexity of this solution is ( O(1) ) because it involves a constant amount of work irrespective of the input size. Parsing, multiplication, and formatting steps are all constant-time operations given the fixed format of the input.
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?