题目描述:
模拟四则运算。
思路:
用栈保存数字,只记录上一个运算符号。每次遍历到一个数字,上一个运算符如果是+,push到栈,-,push当前的相反数,* 或 / ,当前数字和栈顶数字做运算,结果push到栈。最后把栈内数字相加。
代码:
class Solution {
public:
int calculate(string s) {
int len = s.length();
stack<int> st;
char op;
for (int i=0; i<len; ++i) {
if (s[i] == ' ') continue;
else if (s[i] >= '0' && s[i] <= '9') {
int temp = 0;
while(i < len && s[i] >= '0' && s[i] <= '9') {
temp = temp * 10 + (s[i] - '0');
i++;
}
i -= 1;
if (st.empty() || op == '+') {
st.push(temp);
}else if (op == '-') {
st.push(-temp);
}else {
int pre = st.top();
st.pop();
if (op == '*') {
st.push(pre * temp);
} else {
st.push(pre / temp);
}
}
}else op = s[i];
}
int ans = 0;
while(!st.empty()) {
ans = ans + st.top();
st.pop();
}
return ans;
}
};
这个模拟题卡了好久好久好久。。。脑壳痛。
baseline终于出了。。。这个月好像过的有点混乱。
已经过去2/3了。。。心酸。
没有故事的520,心酸。