-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic-calculator-ii.java
43 lines (33 loc) · 1.02 KB
/
basic-calculator-ii.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
// Problem link - https://leetcode.com/problems/basic-calculator-ii/
// TC - O(N)
// SC - O(N)
class Solution {
public int calculate(String s) {
Stack<Integer> st = new Stack<>();
int num = 0;
char operator = '+';
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
// 0-9
if(Character.isDigit(c)){
num = num * 10 + (c - '0');
}
if(isOperator(c) || i == s.length() - 1){
if(operator == '+') st.push(num);
else if (operator == '-') st.push(-num);
else if (operator == '*') st.push(st.pop() * num);
else if (operator == '/') st.push(st.pop() / num);
num = 0;
operator = c;
}
}
int ans = 0;
while(!st.isEmpty()){
ans += st.pop();
}
return ans;
}
private boolean isOperator(char c){
return (c == '+' || c == '-' || c == '*' || c == '/');
}
}