-
Notifications
You must be signed in to change notification settings - Fork 0
/
Basic_Calculator.java
67 lines (55 loc) · 1.79 KB
/
Basic_Calculator.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
62
63
64
65
66
67
/*
224. Basic Calculator
----------------------
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "1 + 1"
Output: 2
Example 2:
Input: s = " 2-1 + 2 "
Output: 3
Example 3:
Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
*/
class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<Integer>();
int result = 0;
int number = 0;
int sign = 1;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
number = 10 * number + (int)(c - '0');
}
else if(c == '+'){
result += sign * number;
number = 0;
sign = 1;
}
else if(c == '-'){
result += sign * number;
number = 0;
sign = -1;
}
else if(c == '('){
//we push the result first, then sign;
stack.push(result);
stack.push(sign);
//reset the sign and result for the value in the parenthesis
sign = 1;
result = 0;
}
else if(c == ')'){
result += sign * number;
number = 0;
result *= stack.pop(); //stack.pop() is the sign before the parenthesis
result += stack.pop(); //stack.pop() now is the result calculated before the parenthesis
}
}
if(number != 0) result += sign * number;
return result;
}
}