Skip to content

537. Complex Number Multiplication

Difficulty Topics

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.

Solution

complex-number-multiplication.py
class Solution:
    def complexNumberMultiply(self, num1: str, num2: str) -> str:

        def parse(nums):
            s = nums.split('+')

            return int(s[0]), int(s[1][:-1])

        n1, i1 = parse(num1)
        n2, i2 = parse(num2)

        n = n1 * n2 - i1 * i2
        i = n1 * i2 + n2 * i1

        return "{}+{}i".format(n, i)