537. Complex Number Multiplication

1. 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].
  • $i^2$ == -1.

Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.

2. Example

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.

3. Constraints

  • num1 and num2 are valid complex numbers.

4. Solutions

Simulation

n = max(num1.size(), num2.size())
Time complexity: O(n)
Space complexity: O(1)

class Solution {
public:
    string complexNumberMultiply(const string &num1, const string &num2) {
        int num1_plus_index = num1.find('+');
        int num1_real = stoi(num1.substr(0, num1_plus_index));
        int num1_imaginary_index = num1_plus_index + (num1[num1_plus_index + 1] == '-' ? 2 : 1);
        int num1_imaginary =
            stoi(num1.substr(num1_imaginary_index, num1.size() - num1_plus_index - 1));
        if (num1_imaginary_index - num1_plus_index == 2) {
            num1_imaginary = -num1_imaginary;
        }

        int num2_plus_index = num2.find('+');
        int num2_real = stoi(num2.substr(0, num2_plus_index));
        int num2_imaginary_index = num2_plus_index + (num2[num2_plus_index + 1] == '-' ? 2 : 1);
        int num2_imaginary =
            stoi(num2.substr(num2_imaginary_index, num2.size() - num2_plus_index - 1));
        if (num2_imaginary_index - num2_plus_index == 2) {
            num2_imaginary = -num2_imaginary;
        }

        int real_part = num1_real * num2_real - num1_imaginary * num2_imaginary;
        int imaginary_part = num1_real * num2_imaginary + num1_imaginary * num2_real;

        string result = to_string(real_part) + "+" + to_string(imaginary_part) + "i";
        return result;
    }
};
comments powered by Disqus