537. Complex Number Multiplication

  • Difficulty: Medium

  • Topics: Math, String

  • Similar Questions:

Problem:

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.
  3. </ol> </p>

    Solutions:

    class Solution {
    public:
        string complexNumberMultiply(string a, string b) {
            auto complex1 = parse(a);
            auto complex2 = parse(b);
    
            int real = complex1.first * complex2.first - complex1.second * complex2.second;
            int img = complex1.first * complex2.second + complex2.first * complex1.second;
    
            return to_string(real) + "+" + to_string(img) + "i";
        }
    
    private:
        pair<int, int> parse(const string& str) {
            int real = 0;
            int img = 0;
            int realSign = 1;
            int imgSign = 1;
    
            int pos = 0;
            if (str[pos] == '-') {
                realSign = -1;
                ++pos;
            }
            while (str[pos] != '+') {
                real = real * 10 + str[pos] - '0';
                ++pos;
            }
    
            ++pos;
    
            if (str[pos] == '-') {
                imgSign = -1;
                ++pos;
            }
            while (str[pos] != 'i') {
                img = 10 * img + str[pos] - '0';
                ++pos;
            }
    
            return {real * realSign, img * imgSign};
        }
    
    };
    

    results matching ""

      No results matching ""