537 复数乘法(中等

简介:

image-20221030160706881

解题思路:用加号作为分隔符,然后取出前后的所有数使用复数运算法则进行计算即可。题解如下,官方代码更简洁。

#
# @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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关文章
|
2月前
|
Python
首先,我们可以从基本的数学运算开始,比如加法、减法、乘法、除法等。
首先,我们可以从基本的数学运算开始,比如加法、减法、乘法、除法等。
|
3月前
537. 复数乘法
537. 复数乘法
|
3月前
|
BI
1051 复数乘法 (15 分)
1051 复数乘法 (15 分)
|
3月前
1034 有理数四则运算 (20 分)
1034 有理数四则运算 (20 分)
|
4月前
leetcode-537:复数乘法
leetcode-537:复数乘法
27 0
|
4月前
|
存储 C++
[C++/PTA] 矩阵的乘法运算
[C++/PTA] 矩阵的乘法运算
119 0
|
11月前
|
机器学习/深度学习
什么是浮点数加减运算里的对阶,阶码和尾数
什么是浮点数加减运算里的对阶,阶码和尾数
|
C++
C++ 超大整数相加、相乘的精确求解,以及10000的阶乘
C++ 超大整数相加、相乘的精确求解,以及10000的阶乘
104 0