您的位置:首页 > 其它

227. Basic Calculator II

2015-12-21 21:37 246 查看
Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers,
+
,
-
,
*
,
/
operators and empty spaces
. The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5


Note: Do not use the
eval
built-in library function.

class Solution {
public:
int calculate(string s) {
stack<int> stack;
int res = 0;
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s[i];
if (isdigit(c)) {
int cur = c - '0';
while (i + 1 < len && isdigit(s[i + 1])) {
cur = cur * 10 + s[i + 1] - '0';
i++;
}
stack.push(cur);
} else if (c == '+') {
if (stack.size() == 1)
stack.push(1);
else {
res = stack.top();
stack.pop();
res = res * stack.top();
stack.pop();
res = res + stack.top();
stack.pop();
stack.push(res);
stack.push(1);
}
} else if (c == '-') {
if (stack.size() == 1)
stack.push(-1);
else {
res = stack.top();
stack.pop();
res = res * stack.top();
stack.pop();
res = res + stack.top();
stack.pop();
stack.push(res);
stack.push(-1);
}
} else if (c == '*') {
//avoid space
while (i + 1 < len && !isdigit(s[i + 1])) {
i++;
}
int cur = s[++i] - '0';
while (i + 1 < len && isdigit(s[i + 1])) {
cur = cur * 10 + s[i + 1] - '0';
i++;
}
res = stack.top() * cur;
stack.pop();
stack.push(res);
} else if (c == '/') {
while (i + 1 < len && s[i + 1] == ' ') {
i++;
}
int cur = s[++i] - '0';
while (i + 1 < len && isdigit(s[i + 1])) {
cur = cur * 10 + s[i + 1] - '0';
i++;
}
res = stack.top() / cur;
stack.pop();
stack.push(res);
}
}
if (stack.size() == 1)
return stack.top();
else {
res = stack.top();
stack.pop();
res = res * stack.top();
stack.pop();
res = res + stack.top();
return res;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: