1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public: int calculate(string s) { vector<int> stk; char preSign = '+'; int n = s.length(), num = 0; for (int i = 0; i < n; ++i) { if (isdigit(s[i])) num = num * 10 + (s[i] - '0'); if ((!isdigit(s[i]) && s[i] != ' ') || i == n - 1) { switch (preSign) { case '+': stk.push_back(num); break; case '-': stk.push_back(-num); break; case '*': stk.back() *= num; break; case '/': stk.back() /= num; } preSign = s[i]; num = 0; } } return accumulate(stk.begin(), stk.end(), 0); } };
|