537. Complex Number Multiplication

题目

https://leetcode.com/problems/complex-number-multiplication/description/

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
string complexNumberMultiply(string a, string b) {
auto i = a.find('+');
int aa = stoi(a.substr(0, i + 1));
int ab = stoi(a.substr(i + 1, a.length() - 1));
auto j = b.find('+');
int ba = stoi(b.substr(0, j + 1));
int bb = stoi(b.substr(j + 1, b.length() - 1));
int ca = aa * ba - ab * bb;
int cb = aa * bb + ab * ba;
return (to_string(ca) + '+' + to_string(cb) + 'i');
}
};

stringstream写起来更简单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
string complexNumberMultiply(string a, string b) {
std::stringstream a_in(a), b_in(b);
int aa, ab, ba, bb;
char tmp;
a_in >> aa >> tmp >> ab >> tmp;
b_in >> ba >> tmp >> bb >> tmp;
std::stringstream ans;
ans << aa * ba - ab * bb << '+' << aa * bb + ab * ba << 'i';
return ans.str();
// return to_string(aa * ba - ab * bb) + '+' + to_string(aa * bb + ab * ba) + 'i';
}
};