-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path150.evaluate-reverse-polish-notation.java
More file actions
43 lines (42 loc) · 1.4 KB
/
150.evaluate-reverse-polish-notation.java
File metadata and controls
43 lines (42 loc) · 1.4 KB
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
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
String now = tokens[i];
if (now.equals("+")){
int b = stack.pop();
int a = stack.pop();
stack.push(a+b);
}else if (now.equals("-")){
int b = stack.pop();
int a = stack.pop();
stack.push(a-b);
}else if (now.equals("*")){
int b = stack.pop();
int a = stack.pop();
stack.push(a*b);
}else if (now.equals("/")){
int b = stack.pop();
int a = stack.pop();
stack.push(a/b);
}else{
stack.push(str2int(now));
}
}
return stack.peek();
}
public int str2int(String number){
int result = 0;
if (number.charAt(0)=='-'){
for (int i = 1; i < number.length(); i++) {
result = 10*result+Character.getNumericValue(number.charAt(i));
}
return -result;
}else {
for (int i = 0; i < number.length(); i++) {
result = 10*result+Character.getNumericValue(number.charAt(i));
}
return result;
}
}
}