Problem
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.
Example 1:
Input: "3+2*2"
Output: 7
Example 2:
Input: " 3/2 "
Output: 1
Example 3:
Input: " 3+5 / 2 "
Output: 5
Note:
You may assume that the given expression is always valid.
Do not use the eval built-in library function.
Solution
class Solution {
public int calculate(String s) {
s = s.trim().replaceAll(" ", "");
if (s == null || s.length() == 0) return 0;
long pre = 0;
int res = 0, i = 0;
char sign = '+';
while (i < s.length()) {
long cur = 0;
while (i < s.length() && Character.isDigit(s.charAt(i))) {
cur = cur*10 + (s.charAt(i)-'0');
i++;
}
switch (sign) {
case '+':
res += pre;
pre = cur; break;
case '-':
res += pre;
pre = -cur; break;
case '*':
pre *= cur; break;
case '/':
pre /= cur; break;
}
if (i < s.length()) {
sign = s.charAt(i);
i++;
}
}
res += pre;
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。