537. Complex Number Multiplication**

537. Complex Number Multiplication**

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

题目描述

Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note i 2 = 1 i^2 = -1 according to the definition.

Example 1:

Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.

Example 2:

Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.

Note:

  • The input strings will not have extra blank.
  • The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.

C++ 实现 1

复数的乘法: (a + bi) * (c + di) = (ac - bd) + (ad + bc)i.

class Solution {
private:
    vector<int> convert_complex_to_vector(const string &s) {
        auto plus_pos = s.find('+');
        auto str_a = s.substr(0, plus_pos);
        auto str_b = s.substr(plus_pos + 1, std::string::npos - plus_pos - 1);
        auto a = std::stoi(str_a), b = std::stoi(str_b);
        return {a, b};
    }
    vector<int> multiply(const vector<int> &v1, const vector<int> &v2) {
        auto a = v1[0], b = v1[1], c = v2[0], d = v2[1];
        auto r = a * c - b * d;
        auto i = a * d + b * c;
        return {r, i};
    }
    string convert_vector_to_complex(const vector<int> &v) {
        auto a = v[0], b = v[1];
        string s = std::to_string(a) + "+" + std::to_string(b) + "i";
        return s;
    }
public:
    string complexNumberMultiply(string a, string b) {
        auto v1 = convert_complex_to_vector(a);
        auto v2 = convert_complex_to_vector(b);
        auto vec_res = multiply(v1, v2);
        auto res = convert_vector_to_complex(vec_res);
        return res;
    }
};

C++ 实现 2

两年前的代码

class Solution {
private:
    pair<int, int> stringToPair(string &comp) {
        auto first = comp.find('+');
        int a = std::stoi(comp.substr(0, first));
        int b = std::stoi(comp.substr(first+1, comp.size() - first - 2));
        return make_pair(a, b);
    }
public:
    string complexNumberMultiply(string a, string b) {
        auto p1 = stringToPair(a);
        auto p2 = stringToPair(b);
        string res = "";
        res += to_string(p1.first * p2.first - p1.second * p2.second);
        res += "+";
        res += to_string(p1.first * p2.second + p1.second * p2.first);
        res += "i";
        return res;
    }
};

发布了227 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104088929