Complex Multiplication in C++ using regex


  • 0
    C
    #include <regex>
    class Solution {
    public:
        string complexNumberMultiply(string a, string b) {
            regex e("([-]*)([0-9]*)([+])([-]*)([0-9]*)([i]*)");
            smatch m1, m2;
            int r1=0,r2=0,i1=0,i2=0;
            regex_search(a,m1,e);
            regex_search(b,m2,e);
               
            r1 = stoi(m1[2].str());
            r2 = stoi(m2[2].str());
            i1 = stoi(m1[5].str());
            i2 = stoi(m2[5].str());
            
            if(m1[1].str() == "-")
                r1 = -r1;
            if(m1[4].str() == "-")
                i1 = -i1;
            if(m2[1].str() == "-")
                r2 = -r2;
            if(m2[4].str() == "-")
                i2 = -i2;
              
            int real = r1*r2 - i1*i2;
            int imag = r1*i2 + r2*i1;
            string res = to_string(real) + "+" + to_string(imag) + "i" ;
            
            return res;
            
        }
    };

  • 0
    L

    "((-|)[0-9]+)\\+((-|)[0-9]+)\\i" is a more appropriate regex


Log in to reply
 

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