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.
题目含义:实现一个计算器
1 public int calculate(String s) { 2 if (s == null || s.length() == 0) return 0; 3 Stack<Integer> stack = new Stack<Integer>(); 4 int number = 0, sign = '+'; 5 for (int i = 0; i < s.length(); i++) { 6 char letter = s.charAt(i); 7 if (Character.isDigit(letter)) number = number * 10 + letter - '0'; 8 if ((!Character.isDigit(letter) && letter != ' ') || (i == s.length() - 1)) { 9 if (sign == '+') stack.push(number); 10 else if (sign == '-') stack.push(-number); 11 else if (sign == '*') stack.push(stack.pop() * number); 12 else if (sign == '/') stack.push(stack.pop() / number); 13 sign = letter; 14 number = 0; 15 } 16 } 17 int result = 0; 18 for (Integer value : stack) { 19 result += value; 20 } 21 return result; 22 }