Wednesday, September 27, 2017

537. Complex Number Multiplication

https://leetcode.com/problems/complex-number-multiplication/description/
Solution 1.stringstream
    string complexNumberMultiply(string a, string b) {
        int ar, ai, br, bi;
        char buff;
        stringstream ssa(a), ssb(b), res;
        ssa >> ar >> buff >> ai >> buff;
        ssb >> br >> buff >> bi >> buff;
        res << ar*br - ai*bi << "+" << ar*bi + br*ai << "i";
        return res.str();
    }
Solution 2. strtok
    string complexNumberMultiply(string a, string b) {
        string ars = strtok((char*)a.c_str(), "+i");
        string ais = strtok(NULL, "+i");
        string brs = strtok((char*)b.c_str(), "+i");
        string bis = strtok(NULL, "+i");
        long ar = stol(ars);
        long ai = stol(ais);
        long br = stol(brs);
        long bi = stol(bis);
        long re = ar*br - ai*bi;
        long im = ar*bi + ai*br;
     
        return to_string(re)+"+"+to_string(im)+"i";
    }

No comments:

Post a Comment