Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Nhân số phức (Complex Number Multiplication) trong C++

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

  1. Phân tích chuỗi lấy phần thực và ảo.
  2. Áp dụng công thức: (a+bi)(c+di) = (ac-bd) + (ad+bc)i.
  3. 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