Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Complex Number Multiplication คูณจำนวนเชิงซ้อนใน C++

ให้สตริง 2 ตัวแทนจำนวนเชิงซ้อน แปลงและคูณกัน แล้วคืนผลลัพธ์เป็นสตริง

ตัวอย่าง: "1+-1i" และ "1+-1i" → "0+-2i"

วิธีแก้ปัญหา (Parse + Formula)

  1. แปลงสตริง a, b เป็นคู่ (real, imaginary) ด้วยฟังก์ชัน parse
  2. คำนวณ: x = a.real*b.real - a.img*b.img, y = a.real*b.img + a.img*b.real
  3. คืนค่า "x+yi"

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    string complexNumberMultiply(string a, string b) {
        pair<int, int> aa = parse(a);
        pair<int, int> 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";
    }
    
    pair<int, int> parse(string s) {
        pair<int, int> ret;
        int plus = find(s.begin(), s.end(), '+') - s.begin();
        int i = find(s.begin(), s.end(), 'i') - s.begin();
        ret.first = stoi(s.substr(0, plus));
        ret.second = stoi(s.substr(plus + 1, i - plus - 1));
        return ret;
    }
};

int main() {
    Solution ob;
    cout << ob.complexNumberMultiply("1+-1i", "1+-1i");
    return 0;
}

Input

"1+-1i" "1+-1i"

Output

0+-2i