-
Notifications
You must be signed in to change notification settings - Fork 1
/
BasicCalculatorII.java
61 lines (52 loc) · 1.56 KB
/
BasicCalculatorII.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.leetcode;
import java.util.Stack;
public class BasicCalculatorII {
//https://leetcode.com/problems/basic-calculator-ii/
/**
Example 1:
Input: s = "3+2*2"
Output: 7
Example 2:
Input: s = " 3/2 "
Output: 1
Example 3:
Input: s = " 3+5 / 2 "
Output: 5
**/
class Solution {
public int calculate(String s) {
int result = 0;
int n = s.length();
Stack<Integer> stack = new Stack<>();
int num = 0;
int op = '+';
for(int i = 0 ; i < n ; i++){
char ch = s.charAt(i);
if(i != n-1 && ch == ' ') continue;//ignore blank. for n-1 we need operation
if(Character.isDigit(ch)){
num = num*10 + ch -'0';
}
if(!Character.isDigit(ch) || i == n-1){
if(op == '+'){
stack.push(num);
}if(op == '-'){
stack.push(-num);
}
if(op == '*'){
stack.push(stack.pop() * num);
}
if(op == '/'){
if(num == 0) return Integer.MAX_VALUE;
stack.push(stack.pop() / num);
}
op = ch;
num = 0;//reset for new number
}
}
while(stack.size() > 0){
result += stack.pop();
}
return result;
}
}
}