[LeetCode]537. Complex Number Multiplication
题目描述
思路
- 自己的想法,构建complex的struct,之后处理每个字符串
- 答案做法,stringstream
代码
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
vector<string> split(string str, char ch) {
string temp;
vector<string> res;
for (char c : str) {
if (c == ch) {
res.push_back(temp);
temp = "";
}
else temp += c;
}
if (temp != "") res.push_back(temp);
return res;
}
struct complex {
int real;
int imag;
complex(string s) {
string real_str, imag_str;
real = 0, imag = 0;
vector<string> res = split(s, '+');
if (res.size() == 1) {
real = res[0].back() == 'i' ? 0 : stoi(res[0]);
imag = res[0].back() == 'i' ? stoi(res[0].substr(0, res[0].size() - 1)) : 0;
}
else {
real = stoi(res[0]);
imag = stoi(res[1].substr(0, res[1].size() - 1));
}
}
};
class Solution {
public:
string complexNumberMultiply(string a, string b) {
complex a_complex = complex(a), b_complex = complex(b);
int res_real = a_complex.real * b_complex.real - a_complex.imag * b_complex.imag,
res_imag = a_complex.real * b_complex.imag + a_complex.imag * b_complex.real;
return to_string(res_real) + "+" + to_string(res_imag) + "i";
}
};
class Solution1 {
public:
string complexNumberMultiply(string a, string b) {
int ra, ia, rb, ib;
char buff;
stringstream aa(a), bb(b), ans;
aa >> ra >> buff >> ia >> buff;
bb >> rb >> buff >> ib >> buff;
ans << ra*rb - ia*ib << "+" << ra*ib + rb*ia << "i";
return ans.str();
}
};
int main() {
Solution1 s;
cout << s.complexNumberMultiply("1+1i", "1+1i") << endl;
system("pause");
return 0;
}