classSolution { public: intcalculate(string s){ int i = 0; s += "+"; return calc(s, i); }
intcalc(conststring &s, int &i){ char op = '+'; long n = s.size(), num = 0, res = 0; for (; i < n; ++i) { char c = s[i]; if (isdigit(c)) { num = num * 10 + c - '0'; } elseif (c == '(') { num = calc(s, ++i); } elseif (c != ' ') { res += (44 - op) * num; // 因为没有*/所以不需要curRes来进行局部运算,直接用res累加即可 op = c; num = 0; if (c == ')') break; } } return res; } };
classSolution { public: intcalculate(string s){ int i = 0; s += "+"; return calc(s, i); }
intcalc(conststring &s, int &i){ char op = '+'; long n = s.size(), num = 0, res = 0; for (; i < n && op != ')'; ++i) { char c = s[i]; if (isdigit(c)) { num = num * 10 + c - '0'; } elseif (c == '(') { num = calc(s, ++i); --i; // 因为最后循环终止条件是op != ')'所以当op为')'时i已经指向下一个符号,所以需要回退一个 } elseif (c != ' ') { res += (44 - op) * num; // 因为没有*/所以不需要curRes来进行局部运算,直接用res累加即可 op = c; num = 0; } } return res; } };