zoukankan      html  css  js  c++  java
  • [LeetCode] Complex Number Multiplication

    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.

    Note:

    1. The input strings will not have extra blank.
    2. The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.

    利用stringstream格式化字符串后计算。

    class Solution {
    public:
        string complexNumberMultiply(string a, string b) {
            int ra, ia, rb, ib;
            char sign;
            stringstream sa(a), sb(b), res;
            sa >> ra >> sign >> ia >> sign;
            sb >> rb >> sign >> ib >> sign;
            res << ra * rb - ia * ib << "+" << ra * ib + rb * ia << "i";
            return res.str();
        }
    };
    // 3 ms

     利用sscanf格式化字符串后计算。

    class Solution {
    public:
        string complexNumberMultiply(string a, string b) {
            int ra, ia, rb, ib;
            sscanf(a.c_str(), "%d+%di", &ra, &ia);
            sscanf(b.c_str(), "%d+%di", &rb, &ib);
            return to_string(ra * rb - ia * ib) + "+" + to_string(ra * ib + rb * ia) + "i";
        }
    };
    // 3 ms

     使用stoi来转换

    使用substr和find分割字符串

    class Solution {
    public:
        string complexNumberMultiply(string a, string b) {
            auto pos = a.find('+');
            int ra = stoi(a.substr(0, pos));
            int ia = stoi(a.substr(pos + 1, a.find('i')));
            pos = b.find('+');
            int rb = stoi(b.substr(0, pos));
            int ib = stoi(b.substr(pos + 1, b.find('i')));
            return to_string(ra * rb - ia * ib) + "+" + to_string(ra * ib + rb * ia) + "i";
        }
    };
    // 3 ms
  • 相关阅读:
    P1352 没有上司的舞会
    P1879 [USACO06NOV]玉米田Corn Fields
    P1896 [SCOI2005]互不侵犯
    2019寒假纪中happy之旅
    JZOJ 4249. 【五校联考7day1】游戏
    JZOJ 4248. 【五校联考7day1】n染色
    JZOJ 4252. 【五校联考7day2】QYQ的图
    STM32初学Keil4编译时出现 Error:Failed to execute 'BIN40/Armcc'
    STM32初学Keil4编译时出现 Error:Failed to execute 'BIN40/Armcc'
    重踏学习Java路上_Day02(java 基础上)
  • 原文地址:https://www.cnblogs.com/immjc/p/8298589.html
Copyright © 2011-2022 走看看