leetcode算法题--复数乘法

原题链接:https://leetcode-cn.com/problems/complex-number-multiplication/
1、 istringstream

class Solution {
public:
    string complexNumberMultiply(string num1, string num2) {
        istringstream s1(num1), s2(num2);
        string str;
        vector<string> vec1, vec2;
        while(getline(s1, str, '+')) vec1.push_back(str);
        while(getline(s2, str, '+')) vec2.push_back(str);
        int a1 = stoi(vec1[0]), a2 = stoi(vec2[0]);
        int b1 = stoi(vec1[1].substr(0, vec1[1].size() - 1)), b2 = stoi(vec2[1].substr(0, vec2[1].size() - 1));
        int a = a1 * a2 - b1 * b2;
        int b = a1 * b2 + a2 * b1;
        return to_string(a) + "+" + to_string(b) + "i";
    }
};

2、regex

class Solution {
public:
    string complexNumberMultiply(string num1, string num2) {
        regex re("\\+|i");// 在 C++ 中 \ 会被作为字符串内的转义符,为使 \+ 作为正则表达式传递进去生效,需要对 \ 进行二次转义,从而有 \\+
        vector<string> vec1(sregex_token_iterator(num1.begin(), num1.end(), re, -1), sregex_token_iterator());
        vector<string> vec2(sregex_token_iterator(num2.begin(), num2.end(), re, -1), sregex_token_iterator());
        int a1 = stoi(vec1[0]), a2 = stoi(vec2[0]);
        int b1 = stoi(vec1[1]), b2 = stoi(vec2[1]);
        int a = a1 * a2 - b1 * b2;
        int b = a1 * b2 + a2 * b1;
        return to_string(a) + "+" + to_string(b) + "i";
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值