Cho hai chuỗi biểu diễn số phức "a+bi", thực hiện phép nhân và trả về chuỗi kết quả.
Ví dụ: "1+-1i" * "1+-1i" = "0+-2i".
Thuật toán
- Phân tích chuỗi lấy phần thực và ảo.
- Áp dụng công thức:
(a+bi)(c+di) = (ac-bd) + (ad+bc)i. - Ghép kết quả thành chuỗi
"x+yi".
Mã nguồn C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
pair<int,int> parse(string s) {
int plus = s.find('+');
int i = s.find('i');
return {stoi(s.substr(0, plus)), stoi(s.substr(plus+1, i-plus-1))};
}
string complexNumberMultiply(string a, string b) {
auto aa = parse(a), bb = parse(b);
int x = aa.first * bb.first - aa.second * bb.second;
int y = aa.first * bb.second + aa.second * bb.first;
return to_string(x) + "+" + to_string(y) + "i";
}
};
int main() {
Solution ob;
cout << ob.complexNumberMultiply("1+-1i", "1+-1i");
return 0;
}
Đầu vào / Đầu ra
Input: "1+-1i" "1+-1i"
Output: 0+-2i