原题链接:https://leetcode-cn.com/problems/complex-number-multiplication/
1、 istringstream
class Solution {
public:
string complexNumberMultiply(string num1, string num2) {
istringstream s1(num1), s2(num2);
string str;
vector<string> vec1, vec2;
while(getline(s1, str, '+')) vec1.push_back(str);
while(getline(s2, str, '+')) vec2.push_back(str);
int a1 = stoi(vec1[0]), a2 = stoi(vec2[0]);
int b1 = stoi(vec1[1].substr(0, vec1[1].size() - 1)), b2 = stoi(vec2[1].substr(0, vec2[1].size() - 1));
int a = a1 * a2 - b1 * b2;
int b = a1 * b2 + a2 * b1;
return to_string(a) + "+" + to_string(b) + "i";
}
};
2、regex
class Solution {
public:
string complexNumberMultiply(string num1, string num2) {
regex re("\\+|i");// 在 C++ 中 \ 会被作为字符串内的转义符,为使 \+ 作为正则表达式传递进去生效,需要对 \ 进行二次转义,从而有 \\+
vector<string> vec1(sregex_token_iterator(num1.begin(), num1.end(), re, -1), sregex_token_iterator());
vector<string> vec2(sregex_token_iterator(num2.begin(), num2.end(), re, -1), sregex_token_iterator());
int a1 = stoi(vec1[0]), a2 = stoi(vec2[0]);
int b1 = stoi(vec1[1]), b2 = stoi(vec2[1]);
int a = a1 * a2 - b1 * b2;
int b = a1 * b2 + a2 * b1;
return to_string(a) + "+" + to_string(b) + "i";
}
};