My 12ms C++ solution


  • 0
    C

    I used the fact that we are only dealing with expressions that are sums of products, so it may not generalize well when we have more operators than given here, or have parentheses. But at least it works well here.

    class Solution {
    public:
        int calculate(string s) {
            int l=s.length();
            if (l==0) return 0;
            bool rec=false; // whether to restart recording numbers
            int num=0; // record the last number found
            int rmd=1,rpm=0; // record the last '+,-' result or '*,/' result calculated so far
            char omd='*',opm='+';  // record the last '+,-' or '*,/' found
            for (int i=0; i<l; i++) {
                if (s[i]==' ') continue;
                else if (s[i]>='0' && s[i]<='9') {
                    if (rec) { num=num*10+(s[i]-'0'); }
                    else { rec=true; num=s[i]-'0'; }
                }
                else if (s[i]=='*' || s[i]=='/') {
                    if (omd=='*') rmd*=num;
                    else rmd/=num;
                    rec=false;
                    omd=s[i];
                }
                else if (s[i]=='+' || s[i]=='-') {
                    if (omd=='*') rmd*=num;
                    else rmd/=num;
                    if (opm=='+') rpm+=rmd;
                    else rpm-=rmd;
                    rmd=1;
                    omd='*';
                    rec=false;
                    opm=s[i];
                }
            }
            // clear the cache
            if (omd=='*') rmd*=num;
            else rmd/=num;
            if (opm=='+') rpm+=rmd;
            else rpm-=rmd;
            return rpm;
        }
    };
    

Log in to reply
 

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