[leetcode]: 537. Complex Number Multiplication

1.题目

Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note i2 = -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.

2.分析

本题主要考点: 从字符串中提取复数
比较笨的方法是遍历字符串,手动提取实部,虚部
便利的方法例如:
c++ stringstream
python split

3.代码

c++ stringstream

class Solution {
public:
    string complexNumberMultiply(string a, string b) {
        int a_Re, a_Im;
        int b_Re, b_Im;
        char buff;
        stringstream A(a), B(b),ans;
        A >> a_Re >> buff >> a_Im >> buff;
        B >> b_Re >> buff >> b_Im >> buff;
        ans << a_Re*b_Re - a_Im*b_Im << "+" << a_Re*b_Im + a_Im*b_Re << "i";
        return ans.str();
    }
};

python split

class Solution(object):
    def complexNumberMultiply(self, a, b):
        ra,ia=map(int,a[:-1].split('+'))
        rb,ib=map(int,b[:-1].split('+'))
        return '%d+%di'%(ra*rb-ia*ib,ra*ib+rb*ia)

手动遍历

class Solution {
public:
    void get_complex(string s, int& Re, int& Im) {
        int i = 0;
        int sign_Re = 1;
        int sign_Im = 1;
        if (s[i] == '-') {
            sign_Re = -1;
            ++i;
        }
        while (s[i] != '+') {
            Re = Re * 10 + s[i] - '0';
            ++i;
        }
        ++i;
        if (s[i] == '-')
        {
            sign_Im = -1;
            ++i;
        }
        while (s[i] != 'i') {
            Im = Im * 10 + s[i] - '0';
            ++i;
        }
        Re *= sign_Re;
        Im *= sign_Im;
    }
    string complexNumberMultiply(string a, string b) {
        int a_Re=0, a_Im = 0;
        int b_Re=0, b_Im = 0;
        get_complex(a, a_Re, a_Im);
        get_complex(b, b_Re, b_Im);
        int Re = a_Re*b_Re - a_Im*b_Im;
        int Im = a_Re*b_Im + a_Im*b_Re;
        return to_string(Re) + "+" + to_string(Im) + "i";
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值