Easy Method C++ 9ms


  • 0
    L
        int calculate(string s) {
            int len = s.size(), curRst = 0, preNum = 0, curNum = 0, index = 0;
            char sign = '+';
            while(index < len)
            {
                char ch = s[index];
                index ++;
                if(isdigit(ch)) curNum = curNum * 10 + (ch - '0');
                else
                {
                    if(ch == ' ') continue;
                    if(sign == '+') 
                    {
                        curRst = curRst + curNum;
                        preNum = curNum;
                    }
                    if(sign == '-')
                    {
                        curRst = curRst - curNum;
                        preNum = -curNum;
                    }
                    if(sign == '*')
                    {
                        curRst = curRst - preNum + preNum * curNum;
                        preNum = preNum * curNum;
                    }
                    if(sign == '/')
                    {
                        curRst = curRst - preNum + preNum/curNum;
                        preNum = preNum/curNum;
                    }
                    curNum = 0;
                    sign = ch;
                }
            }
            if(sign == '+') curRst = curRst + curNum;
            if(sign == '-') curRst = curRst - curNum;
            if(sign == '*') curRst = curRst - preNum + preNum * curNum;
            if(sign == '/') curRst = curRst - preNum + preNum/curNum;
            return curRst;
        }
    

Log in to reply
 

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