C++ substr easy to understand


  • 0
    L
    class Solution {
    public:
        string complexNumberMultiply(string a, string b) {
            int m  = 0,n = 0,c = 0,d = 0;
            for(int i = 0 ; i < a.size();++i){
                if(a[i] == '+'){
                    m  = atoi(a.substr(0,i).c_str());
                    if(a[i+1] == '-')
                        n = -atoi(a.substr(i+2,a.size()-i-2).c_str());
                    else
                        n = atoi(a.substr(i+1,a.size()-i-1).c_str());
                    break;
                }
            }
            for(int i = 0 ; i < b.size();++i){
                if(b[i] == '+'){
                    c  = atoi(b.substr(0,i).c_str());
                    if(b[i+1] == '-')
                        d = -atoi(b.substr(i+2,b.size()-i-2).c_str());
                    else
                        d = atoi(b.substr(i+1,b.size()-i-1).c_str());
                    break;
                }
            }
            int real = m*c-n*d;
            int imag = m*d+n*c;
            string res = to_string(real)+"+"+to_string(imag)+"i";;
           
    
            return res;
        }
    };
    

Log in to reply
 

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