-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
28 lines (26 loc) · 902 Bytes
/
Calculator.java
File metadata and controls
28 lines (26 loc) · 902 Bytes
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
package CommonQuestions;
import java.util.Stack;
public class Calculator {
int i = 0;
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
char operator = '+';
int n = 0;
while(i < s.length()){
char c = s.charAt(i);
i++;
if(Character.isDigit(c)) n = n * 10 + (c - '0');
if(c == '(') n = calculate(s);
if(i >= s.length() || c == '+' || c == '-' || c == '*' || c == '/' || c == ')'){
if(operator == '+') stack.add(n);
if(operator == '-') stack.add(-n);
if(operator == '*') stack.add(stack.pop() * n);
if(operator == '/') stack.add(stack.pop() / n);
operator = c;
n = 0;
}
if(c == ')') break;
}
return stack.stream().mapToInt(x -> x).sum();
}
}