537. Complex Number Multiplication (Medium)

Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note i2 = -1 according to the definition.

Example 1:

Input: "1+1i", "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: "1+-1i", "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.

Note:

  1. The input strings will not have extra blank.
  2. The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.

Summary

Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note $$i^2$$ = -1 according to the definition.

Solution


Approach #1 Simple Solution[Accepted]

Algorithm

Multiplication of two complex numbers can be done as: $$(a+ib)*(x+iy)=ax+i^2by+i(bx+ay)=ax−by+i(bx+ay)$$

We simply split up the real and the imaginary parts of the given complex strings based on the '+' and the 'i' symbols. We store the real parts of the two strings $$a$$ and $$b$$ as $$x[0]$$ and $$y[0]$$ respectively and the imaginary parts as $$x[1]$$ and $$y[1]$$ respectively. Then, we multiply the real and the imaginary parts as required after converting the extracted parts into integers. Then, we again form the return string in the required format and return the result.

cpp 3ms

class Solution {
public:
    string complexNumberMultiply(string a, string b) {
        a.pop_back(); b.pop_back();
        size_t pos = a.find_first_of('+');
        int a_real = stoi(a.substr(0, pos)), a_img = stoi(a.substr(pos+1));
        pos = b.find_first_of('+');
        int b_real = stoi(b.substr(0, pos)), b_img = stoi(b.substr(pos+1));
        return to_string(a_real*b_real-a_img*b_img)+'+'+to_string(a_real*b_img+a_img*b_real)+'i';
    }
};

Complexity Analysis

  • Time complexity: $$O(1)$$. Splitting and Multiplication take constant time.
  • Space complexity: $$O(1)$$. Constant extra space is used.

results matching ""

    No results matching ""