[537. Complex Number Multiplication] C++_AC


  • 0
     class Solution {
    public:
    string complexNumberMultiply(string a, string b) {
        auto A = getNum(a);
        auto B = getNum(b);
        int real = A.first * B.first + A.second * B.second * -1;
        int i = A.first * B.second + A.second * B.first;
        return to_string(real) + '+' + to_string(i) + 'i';
    }
    
    pair<int,int> getNum(string& s){
        if(s.empty()) return {};
        int real = 0, im = 0;
        int i = 0;
        int sign_r = 1, sign_im = 1;
        if(s[i] == '-'){
            sign_r = -1;
            i++;
        }else if(s[i] == '+'){i++;}
        while(isdigit(s[i])){
            real = real * 10 + (s[i++] - '0');
        }
        while(!isdigit(s[i])){
            if(s[i] == '-') sign_im = sign_im * -1;
            i++;
        }
        while(s[i] != 'i'){
            im = im * 10 + (s[i++] - '0');
        }
        
        return {real * sign_r, im * sign_im};
    }
    };

Log in to reply
 

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