[LeetCode] 537. Complex Number Multiplication

题目比较简单,实现一个复数乘法,输入输出都要求为字符串形式

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.

大部分时间都花在写正则匹配实部和虚部了

两个复数
\(a + bi\), \(c + di\)

\((a + bi) * (c + di) = (ac - bd) + (bc + ad)i\)

使用三个辅助变量

\[\begin{cases} t_1 = (a - b) * (c + d) \\ t_2 = a * d \\ t_3 = b * c \\ \end{cases},\]

\((a + bi) * (c + di) = (t_1 - t_2 + t_3) + (t_2 + t_3)i\)

这样可以把四次乘法减少到三次

string complexNumberMultiply(string a, string b) {
        regex complex_regex("(.*?)\\+(.*?)i");
        
        int a_real = 0;
        int a_imaginary = 0;
        
        int b_real = 0;
        int b_imaginary = 0;
        
        smatch a_complex_match;
        if (std::regex_search(a, a_complex_match, complex_regex))
        {
            a_real = stoi(a_complex_match[1]);
            a_imaginary  = stoi(a_complex_match[2]);
        }
        
        smatch b_complex_match;
        if (std::regex_search(b, b_complex_match, complex_regex))
        {
            b_real = stoi(b_complex_match[1]);
            b_imaginary  = stoi(b_complex_match[2]);
        }
        
        int t1 = (a_real - a_imaginary) * (b_real + b_imaginary);
        int t2 = (a_real * b_imaginary);
        int t3 = (a_imaginary * b_real);
        
        return to_string(t1 - t2 + t3) + "+" + to_string(t2 + t3) + "i";
    }

再看看leetcode上其他人写的代码

用stringstream来读取实部和虚部

-1+-2i

-1 + -2 +
int char int char

aa >> ra >> buff >> ia >> buff

string complexNumberMultiply(string a, string b) {
        stringstream aa(a), bb(b), ans;
        int ra, ia, rb, ib;
        char buff;
        aa >> ra >> buff >> ia >> buff;
        bb >> rb >> buff >> ib >> buff;
        ans << ra * rb - ia * ib <<"+" << ra * ib + rb * ia << "i";
        return ans.str();
    }

参照这份代码对我的代码做一些修改,去掉正则部分,改用stringstream, 最终代码如下

string complexNumberMultiply(string a, string b) 
{
    int a_real, a_imaginary = 0;
    int b_real, b_imaginary = 0;
    char buff;

    stringstream ss_a(a);
    stringstream ss_b(b);
    ss_a >> a_real >> buff >> a_imaginary;
    ss_b >> b_real >> buff >> b_imaginary;

    int t1 = (a_real - a_imaginary) * (b_real + b_imaginary);
    int t2 = (a_real * b_imaginary);
    int t3 = (a_imaginary * b_real);

    return to_string(t1 - t2 + t3) + "+" + to_string(t2 + t3) + "i";
}
posted @ 2018-07-20 17:42  arcsinW  阅读(109)  评论(0编辑  收藏  举报