Skip to content

Commit e258e1f

Browse files
committed
commit
1 parent 3e80d90 commit e258e1f

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public int calculate(String s) {
3+
Stack<Integer> stack = new Stack<Integer>();
4+
int result = 0;
5+
int number = 0;
6+
int sign = 1;
7+
for(int i = 0; i < s.length(); i++){
8+
char c = s.charAt(i);
9+
if(Character.isDigit(c)){
10+
number = 10 * number + (int)(c - '0');
11+
}else if(c == '+'){
12+
result += sign * number;
13+
number = 0;
14+
sign = 1;
15+
}else if(c == '-'){
16+
result += sign * number;
17+
number = 0;
18+
sign = -1;
19+
}else if(c == '('){
20+
//we push the result first, then sign;
21+
stack.push(result);
22+
stack.push(sign);
23+
//reset the sign and result for the value in the parenthesis
24+
sign = 1;
25+
result = 0;
26+
}else if(c == ')'){
27+
result += sign * number;
28+
number = 0;
29+
result *= stack.pop(); //stack.pop() is the sign before the parenthesis
30+
result += stack.pop(); //stack.pop() now is the result calculated before the parenthesis
31+
32+
}
33+
}
34+
if(number != 0) result += sign * number;
35+
return result;
36+
}
37+
}
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Basic Calculator
2+
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
3+
4+
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
5+
```
6+
Example 1:
7+
8+
Input: s = "1 + 1"
9+
Output: 2
10+
Example 2:
11+
12+
Input: s = " 2-1 + 2 "
13+
Output: 3
14+
Example 3:
15+
16+
Input: s = "(1+(4+5+2)-3)+(6+8)"
17+
Output: 23
18+
19+
Constraints:
20+
21+
1 <= s.length <= 3 * 105
22+
s consists of digits, '+', '-', '(', ')', and ' '.
23+
s represents a valid expression.
24+
'+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid).
25+
'-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
26+
There will be no two consecutive operators in the input.
27+
Every number and running calculation will fit in a signed 32-bit integer.

0 commit comments

Comments
 (0)