0 ms C++ solution


  • 1
    V
    class Solution {
    public:
        string complexNumberMultiply(string a, string b) {
            // (a1 + a2 i) * (b1 + b2 i) = (a1b1 - a2b2) + (a1b2 + a2b1) i
            size_t pos = a.find('+');
            int a1 = stoi(a.substr(0, pos)), a2 = stoi(a.substr(pos + 1, a.size() - pos - 2));
            pos = b.find('+');
            int b1 = stoi(b.substr(0, pos)), b2 = stoi(b.substr(pos + 1, b.size() - pos - 2));
            int c1 = a1 * b1 - a2 * b2, c2 = a1 * b2 + a2 * b1;
            return to_string(c1) + "+" + to_string(c2) + "i";
        }
    };
    

  • 0
    Z

    Using 'stoi' instead of 'atoi' is really a good skill~
    It saves 3ms runtime :)
    thx~


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.