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 class Solution227 {
public int calc(int a, int b, char ch) {
if(ch == '+') return a+b;
else if(ch == '-') return a-b;
else if(ch == '*') return a*b;
else if (ch == '/') return a/b;
return 0;
}
public int calculate(String s) {
Map<Character,Integer> map = new HashMap<Character, Integer>();
map.put('+', 1);
map.put('-',1);
map.put('*', 2);
map.put('/',2);
Stack<Integer> number = new Stack<Integer>();
Stack<Character> operator = new Stack<Character>();
if (s.length() <= 0 || s == null) return 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if(ch == '+' || ch == '-' || ch == '*' || ch == '/') {
while (!operator.isEmpty()) {
Character top = operator.peek();
if (map.get(ch) <= map.get(top)) {
top = operator.pop();
int num2 = number.pop(), num1 = number.pop();
int ans = calc(num1, num2, top);
number.push(ans);
} else {
break;
}
}
operator.push(ch);
}else if(ch >= '0' && ch <= '9') {
int tmp = 0;
while (i < s.length()) {
ch = s.charAt(i);
if(ch >= '0' && ch <= '9') {
tmp = tmp * 10 + ch - '0';
} else {
break;
}
i += 1;
}
number.push(tmp);
//System.out.println("**"+tmp);
i -= 1;
}
}
int ans = number.peek();
while (!operator.isEmpty()) {
char ch = operator.pop();
int num2 = number.pop(), num1 = number.pop();
ans = calc(num1, num2, ch);
number.push(ans);
}
return ans;
}
public static void main(String[] args) {
Solution227 ans = new Solution227();
String str = " 1*2-3/4 + 5*6 - 7*8 + 9/10";
int res = ans.calculate(str);
System.out.println(res);
}
}
本文介绍了一个简单的表达式计算器实现,该计算器能够解析并计算包含基本算术运算符(加、减、乘、除)的非负整数表达式。文章通过示例展示了如何使用栈来处理操作数和运算符,并提供了完整的Java代码实现。

被折叠的 条评论
为什么被折叠?



