537. Complex Number Multiplicati

2018-01-19  本文已影响0人  caisense

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:

The input strings will not have extra blank.
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.

思路:主要难点是将字符串转换为实数,用两个int分别存储下其实部和虚部,然后用实数公式计算出结果即可.字符串转int有一些trick,见注释.

class Solution {
public:
    string complexNumberMultiply(string a, string b) {
        int a_r = stoi(a); // trick:字符串直接转int,结果是串首的int,为a的实部
        int p_idx = a.find('+');
        int i_idx = a.find('i');
        int a_v = stoi(a.substr(p_idx+1, i_idx-p_idx)); // 截取表示虚部的子串,再转int,为a的虚部
        // b的处理同上
        int b_r = stoi(b);
        p_idx = b.find('+');
        i_idx = b.find('i');
        int b_v = stoi(b.substr(p_idx+1, i_idx-p_idx));
        
        int r = a_r*b_r + a_v*b_v*-1;
        int v = a_v*b_r + b_v*a_r;
        // 结果再转成string
        string res_r = to_string(r);
        string res_v = to_string(v);
        string res = res_r + "+" + res_v + "i";
        return res;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读