解题思路:用加号作为分隔符,然后取出前后的所有数使用复数运算法则进行计算即可。题解如下,官方代码更简洁。
#
# @lc app=leetcode.cn id=537 lang=python3
#
# [537] 复数乘法
#
# @lc code=start
from re import I
class Solution:
def complexNumberMultiply(self, num1: str, num2: str) -> str:
#我的代码
# num1 = num1.split('+')
# num2 = num2.split('+')
# a1, a2 = int(num1[0]), int(num2[0])
# b1, b2 = int(num1[1][:(len(num1[1])-1)]
# ), int(num2[1][:(len(num2[1])-1)])
# a = a1*a2-b1*b2
# b = a1*b2+a2*b1
# return str(a)+'+'+str(b)+'i'
# leetcode官方题解
real1, img1 = map(int, num1[:-1].split('+'))
real2, img2 = map(int, num2[:-1].split('+'))
return f'{real1*real2-img1*img2}+{real1*img2+img1*real2}i'
# @lc code=end
#学习python代码中map函数的用法
//官方C++代码,使用正则表达式
class Solution {
public:
string complexNumberMultiply(string num1, string num2) {
regex re("\\+|i");
vector<string> complex1(sregex_token_iterator(num1.begin(), num1.end(), re, -1), std::sregex_token_iterator());
vector<string> complex2(sregex_token_iterator(num2.begin(), num2.end(), re, -1), std::sregex_token_iterator());
int real1 = stoi(complex1[0]);
int imag1 = stoi(complex1[1]);
int real2 = stoi(complex2[0]);
int imag2 = stoi(complex2[1]);
return to_string(real1 * real2 - imag1 * imag2) + "+" + to_string(real1 * imag2 + imag1 * real2) + "i";
}
};
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/complex-number-multiplication/solution/fu-shu-cheng-fa-by-leetcode-solution-163i/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。