[leetcode] problem 227 – basic calculator ii

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

No.1

Input: “3+2*2”

Output: 7

No.2

Input: “ 3/2 “

Output: 1

No.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.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public int (String s) {
int result = 0;
int curResult = 0;
int num = 0;
char lastSign = '+';

for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);

if (Character.isDigit(ch)) {
num = 10 * num + (ch - '0');
}

if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || i == s.length() - 1) {
switch (lastSign) {
case '+': curResult += num; break;
case '-': curResult -= num; break;
case '*': curResult *= num; break;
case '/': curResult /= num; break;
}

if (ch == '+' || ch == '-' || i == s.length() - 1) {
result += curResult;
curResult = 0;
}

lastSign = ch;
num = 0;
}
}

return result;
}