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.public int calculate(String s) {
int res = 0;
int num = 0;
char lastOp = '+';
Stack<Integer> stk = new Stack<Integer>();
for (int i = 0; i <= s.length(); i++) {
if (i != s.length() && s.charAt(i) == ' ') {
continue;
} else if (i != s.length() && Character.isDigit(s.charAt(i))) {
num *= 10;
num += s.charAt(i) - '0';
} else {
if (lastOp == '+') {
stk.push(num);
} else if (lastOp == '-') {
stk.push(-num);
} else if (lastOp == '*') {
stk.push(num * stk.pop());
} else if (lastOp == '/') {
stk.push(stk.pop() / num);
}
if (i != s.length())
lastOp = s.charAt(i);
num = 0;
}
}
while (!stk.isEmpty()) {
res += stk.pop();
}
return res;
}
}
=========
public class Solution {
public int calculate(String s) {
int res = 0;
int cur = 0;
int curRes = 0;
char op = '+';
for (int i = 0; i <= s.length(); i++) {
if (i != s.length() && s.charAt(i) == ' ') continue;
if (i != s.length() && Character.isDigit(s.charAt(i))) {
cur *= 10;
cur += s.charAt(i) - '0';
} else {
if (op == '+') {
res += curRes;
curRes = cur;
} else if (op == '-') {
res += curRes;
curRes = -cur;
} else if (op == '*') {
curRes *= cur;
} else {
curRes /= cur;
}
cur = 0;
if (i != s.length()) op = s.charAt(i);
}
}
return res + curRes;
}
}
没有评论:
发表评论