Accepted C++ 16ms O(n) time complexity, O(1) space, using "switch-case"


  • 0
    H

    Maybe "switch-case" structure is better to be used for this problem.
    My solution as follows:

    class Solution
    {
    public:
      int calculate(string s) {
        int pre_sign = 1,res=0,cur_num=0,next_num=0;
        const size_t &len = s.length();
        for(size_t i = 0;i < len;++i)
        {
          const char &c = s[i];
          if(c == ' ') continue;
          switch(c)
          {
          case '+':
          case '-':
            res += cur_num*pre_sign;
            pre_sign = c=='+'?1:-1;
            cur_num = 0;
            break;
          case '/':
          case '*':
            while(i < len - 1 && s[i + 1] == ' ') ++i;
            while(i < len - 1 && isdigit(s[i + 1])) next_num = next_num * 10 + s[++i] - '0';
            if(c == '/') cur_num /= next_num;
            else cur_num *= next_num;
            next_num = 0;
            break;
          default:
            cur_num = cur_num * 10 + c - '0';
            break;
          }
        }
        res += cur_num*pre_sign;
        return res;
      }
    };

Log in to reply
 

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