-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluateReversePolishNotation.java
More file actions
52 lines (51 loc) · 1.69 KB
/
EvaluateReversePolishNotation.java
File metadata and controls
52 lines (51 loc) · 1.69 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
44
45
46
47
48
49
50
51
52
/*
*["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
*["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
*/
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack();
for(int i=0;i<tokens.length;i++){
char [] num = tokens[i].toCharArray();
int num1=0,num2=0;
boolean isNum = true;
for(int j=0;j<num.length;j++){
if(num[0] == '-' && num.length>1){ //判断'-'号,负数
continue;
}
if(!Character.isDigit(num[j])){
isNum = false;
}
}
if(isNum){
stack.push(Integer.parseInt(tokens[i]));
}else {
switch(num[0]){
case '+':
num1 = stack.pop();
num2 = stack.pop();
stack.push(num2+num1);
break;
case '-':
num1 = stack.pop();
num2 = stack.pop();
stack.push(num2-num1);
break;
case '/':
num1 = stack.pop();
num2 = stack.pop();
stack.push(num2/num1);
break;
case '*':
num1 = stack.pop();
num2 = stack.pop();
stack.push(num2*num1);
break;
default:
break;
}
}
}
return stack.pop();
}
}