My 16 ms No stack One pass short C++ solution


  • 37
    F
    class Solution {
    public:
        int calculate(string s) {
            int result = 0, cur_res = 0;
            char op = '+';
            for(int pos = s.find_first_not_of(' '); pos < s.size(); pos = s.find_first_not_of(' ', pos)) {
                if(isdigit(s[pos])) {
                    int tmp = s[pos] - '0';
                    while(++pos < s.size() && isdigit(s[pos]))
                        tmp = tmp*10 + (s[pos] - '0');
                    switch(op) {
                        case '+' : cur_res += tmp; break;
                        case '-' : cur_res -= tmp; break;
                        case '*' : cur_res *= tmp; break;
                        case '/' : cur_res /= tmp; break;
                    }
                }
                else {
                    if(s[pos] == '+' || s[pos] == '-') {
                        result += cur_res;
                        cur_res = 0;
                    }
                    op = s[pos++];
                }
            }
            return result + cur_res;
        }
    };

  • -1
    J

    I have met a strange problem, when I run your code, I set {s.size()} as a variable like {length}, and put it into the loop as a condition. As a result it will cause TLE. I don't know why.
    int calculate(string s) {
    int result = 0, cur_res = 0, length = s.size();
    char op = '+';
    for(int pos = s.find_first_not_of(' '); pos < length; pos = s.find_first_not_of(' ', pos)) {
    if(isdigit(s[pos])) {
    int tmp = s[pos] - '0';
    while(++pos < s.size() && isdigit(s[pos]))
    tmp = tmp10 + (s[pos] - '0');
    switch(op) {
    case '+' : cur_res += tmp; break;
    case '-' : cur_res -= tmp; break;
    case '
    ' : cur_res *= tmp; break;
    case '/' : cur_res /= tmp; break;
    }
    }
    else {
    if(s[pos] == '+' || s[pos] == '-') {
    result += cur_res;
    cur_res = 0;
    }
    op = s[pos++];
    }
    }
    return result + cur_res;
    }


  • 0
    K

    This solution is beautiful. Thanks.


  • 0
    T

    said in My 16 ms No stack One pass short C++ solution:

    cur_res += tmp;

    can be changed to

    cur_res = tmp;

    and

    cur_res -= tmp;

    can be changed to

    cur_res = -tmp;

    . That will be easier to understand.


  • 0
    A

    This case fires exception with this code. Maybe my understanding of "contains empty spaces" is too frivolous.
    if (s.calculate(" 1 0 0 0 / 5 0 0") != 2)
    throw int(-4);


Log in to reply
 

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