class Solution {
public:
int calculate(string s) {
vector<int> ans;
int flag = 1;
s = s + "+0";
int n = s.size();
char preSign = '+'; //上一个运算符
long long num = 0;
for(int i = 0; i < n; i++){
if(s[i] == ' ')
continue;
if(isdigit(s[i]))
num = num * 10 + s[i] - '0';
else{
switch (preSign)
{
case '+':
ans.push_back(num);
break;
case '-':
ans.push_back(-num);
break;
case '*':
ans.back() *= num;
break;
case '/':
ans.back() /= num;
break;
default:
break;
}
preSign = s[i]; //更新运算符
num = 0; //重置当前的数值
}
}
return accumulate(ans.begin(), ans.end(), 0);
}
};
Accepted
109/109 cases passed (8 ms)
Your runtime beats 76.91 % of cpp submissions
Your memory usage beats 11.11 % of cpp submissions (9.3 MB)