A complex number can be represented as a string on the form "real+imaginaryi"
where:
real
is the real part and is an integer in the range [-100, 100]
. For example, in the string "1+2i", the real part is 1.imaginary
is the imaginary part and is an integer in the range [-100, 100]
. For example, in the string "1+2i", the imaginary part is 2.i^2 == -1
.Given two complex numbers num1
and num2
as strings, return a string of the complex number that represents their multiplications.
Example 1:
Input: num1 = "1+1i", num2 = "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i^2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Example 2:
Input: num1 = "1+-1i", num2 = "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i^2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
Write a function to perform this complex number multiplication, considering the constraints and edge cases, and aiming for an optimal solution.
The most straightforward way to solve this problem is to parse the input strings to extract the real and imaginary parts, perform the complex number multiplication, and then format the result back into the required string format.
Steps:
Code (Python):
def complexNumberMultiply(num1: str, num2: str) -> str:
def parse_complex(num: str) -> tuple[int, int]:
real, imaginary = num.split('+')
imaginary = imaginary[:-1]
return int(real), int(imaginary)
real1, imaginary1 = parse_complex(num1)
real2, imaginary2 = parse_complex(num2)
real_part = (real1 * real2) - (imaginary1 * imaginary2)
imaginary_part = (real1 * imaginary2) + (real2 * imaginary1)
return f"{real_part}+{imaginary_part}i"
Explanation:
parse_complex
function extracts the real and imaginary parts from the input string.The provided naive solution is already optimal as the complex number multiplication takes constant time. No other approach could theoretically provide better time complexity.
Edge Cases: