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].imaginary is the imaginary part and is an integer in the range [-100, 100].i2 == -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 + i2 + 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 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
Constraints:
num1 and num2 are valid complex numbers.This approach involves parsing the given strings to separate the real and imaginary components of each complex number. Once separated, apply the distributive property of multiplication for complex numbers: (a+bi)(c+di) = ac + adi + bci + bdi^2. Substitute i^2 with -1 and then combine the real and imaginary parts for the final output string.
In this C solution, we use the sscanf function to parse the real and imaginary parts of the complex numbers. Then, we compute the real and imaginary components of the product using the multiplication formula for complex numbers. Finally, we format the result back into a string with sprintf.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1) because the operations are constant-time.
Space Complexity: O(1) since it only uses a fixed amount of space for the variables and a small dynamic allocation for the output string.
In this approach, regular expressions are used to parse the complex number strings. This involves defining a regex pattern to capture the real and imaginary components. After extracting these components, multiplication is performed using the same algebraic rules, and the result is formatted for output.
Using re.match in Python with a regular expression captures the real and imaginary parts directly. The parsed integers are used for multiplication, with results formatted back into strings in the expected form using Python's f-string syntax.
JavaScript
Time Complexity: O(1) since the regex operation is effectively constant time for fixed-size strings.
Space Complexity: O(1) involving fixed-size auxiliary storage for components and result.
| Approach | Complexity |
|---|---|
| Parse and Multiply Components | Time Complexity: O(1) because the operations are constant-time. |
| Regular Expression Parsing | Time Complexity: O(1) since the regex operation is effectively constant time for fixed-size strings. |
Multiplying Complex Numbers • The Organic Chemistry Tutor • 206,522 views views
Watch 9 more video solutions →Practice Complex Number Multiplication with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor