LeetCode 0537. Complex Number Multiplication Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0537. Complex Number Multiplication

Description

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.

Solutions

Solution 1: Simulation

We can convert the complex number string into its real part a and imaginary part b, and then use the formula for complex number multiplication (a_1 + b_1i) × (a_2 + b_2i) = (a_1a_2 - b_1b_2) + (a_1b_2 + a_2b_1)i to calculate the result.

The time complexity is O(1), and the space complexity is O(1).

PythonJavaC++GoTypeScript
class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: a1, b1 = map(int, num1[:-1].split("+")) a2, b2 = map(int, num2[:-1].split("+")) return f"{a1 * a2 - b1 * b2}+{a1 * b2 + a2 * b1}i"(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !