Friday, August 21, 2020

537. Complex Number Multiplication ------ M

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.

A:

就是个实现题

class Solution {
public:
    string complexNumberMultiply(string a, string b) {
        auto va = getComplex(a);
        auto vb = getComplex(b);
        int c1 = va[0], i1 = va[1];
        int c2 = vb[0], i2 = vb[1];
        int resC = c1*c2 - i1*i2;
        int resI = c1*i2 + c2*i1;
        return to_string(resC) + "+"+to_string(resI) + "i";
    }
private:
    vector<int> getComplex(string str){
        if(str[0]=='+')
            str = str.substr(1);
        int n = str.length();
        int plusIndex = str.find('+');
        int a = stoi(str.substr(0,plusIndex));
        int b = stoi(str.substr(plusIndex+1, str.length() -2-plusIndex ));
        return vector<int>{a,b};
    }
};


No comments:

Post a Comment