[LeetCode]537. Complex Number Multiplication

复数相乘

Posted by JinFei on August 24, 2021

题目描述

A complex number can be represented as a string on the form “real+imaginaryi” where:

  • real is the real part and is an integer in the range [-100, 100].
  • imaginary is the imaginary part and is an integer in the range [-100, 100].
  • i^2 == -1.
  • Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.

Example 1:

Input: num1 = “1+1i”, num2 = “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: num1 = “1+-1i”, num2 = “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.

Constraints:

  • num1 and num2 are valid complex numbers.

解题思路

  • 字符串的基本操作,有find,substr,stoi(目前这个容易记,string2int)不回再记反什么的

C++代码 层次遍历

class Solution {
public:
    pair<int, int> parse(string num){
        int pos = num.find('+');
        int real = stoi(num.substr(0, pos));
        int imaginary = stoi(num.substr(pos + 1, num.size() - pos - 2));
        pair<int, int> res(real, imaginary);
        return res;
    }
    string complexNumberMultiply(string num1, string num2) {
        pair<int, int> a = parse(num1), b = parse(num2);
        int real_a = a.first, imaginary_a = a.second;
        int real_b = b.first, imaginary_b = b.second;
        return to_string(real_a * real_b - imaginary_a * imaginary_b) + "+" + to_string(real_a * imaginary_b + real_b * imaginary_a) + "i";
    }
};