Complex Number Multiplication

To multiply two complex numbers, we can use the distributive property. If we have two complex numbers ( a + bi ) and ( c + di ), their product will be ( ac + adi + bci - bd ), as ( i^2 = -1 ).

We can extract the real and imaginary parts of the given strings and perform the multiplication. Here’s how we can do it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def complexNumberMultiply(self, num1: str, num2: str) -> str:
        # Split the strings into real and imaginary parts
        real1, imaginary1 = map(int, num1[:-1].split('+'))
        real2, imaginary2 = map(int, num2[:-1].split('+'))

        # Compute the product
        real_product = real1 * real2 - imaginary1 * imaginary2
        imaginary_product = real1 * imaginary2 + real2 * imaginary1

        # Return the result in the required format
        return f"{real_product}+{imaginary_product}i"

Explanation:

  • We first split the given strings into the real and imaginary parts, and convert them to integers.
  • We then compute the real part of the product by multiplying the real parts and subtracting the product of the imaginary parts.
  • We compute the imaginary part of the product by multiplying the real part of one number with the imaginary part of the other and adding the results.
  • Finally, we format the result as a string and return it.