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.
思路:主要難點(diǎn)是將字符串轉(zhuǎn)換為實(shí)數(shù),用兩個(gè)int分別存儲(chǔ)下其實(shí)部和虛部,然后用實(shí)數(shù)公式計(jì)算出結(jié)果即可.字符串轉(zhuǎn)int有一些trick,見注釋.
class Solution {
public:
string complexNumberMultiply(string a, string b) {
int a_r = stoi(a); // trick:字符串直接轉(zhuǎn)int,結(jié)果是串首的int,為a的實(shí)部
int p_idx = a.find('+');
int i_idx = a.find('i');
int a_v = stoi(a.substr(p_idx+1, i_idx-p_idx)); // 截取表示虛部的子串,再轉(zhuǎn)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;
// 結(jié)果再轉(zhuǎn)成string
string res_r = to_string(r);
string res_v = to_string(v);
string res = res_r + "+" + res_v + "i";
return res;
}
};