-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvaluate Reverse Polish Notation
95 lines (91 loc) · 2.3 KB
/
Evaluate Reverse Polish Notation
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
*Evaluate Reverse Polish Notation
*valuate the value of an arithmetic expression in Reverse Polish Notation.
*Valid operators are +, -, *, /. Each operand may be an integer or another expression.
*Some examples:
* ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
* ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
*/
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> ex=new Stack<Integer>();
for(String i:tokens)
{
if(isNum(i))
{
ex.push(stonum(i));
}
else
{
int first =ex.pop();
int last=ex.pop();
switch(i)
{
case "+":
ex.push(last+first);
break;
case "/":
ex.push(last/first);
break;
case "*":
ex.push(last*first);
break;
case "-":
ex.push(last-first);
break;
default:
break;
}
}
}
return ex.pop();
}
private boolean isNum(String str)
{
if(str.charAt(0)=='-'&&str.length()>1)
{
return true;
}
else
{
for(int i=str.length();--i>=0;)
{
int chr=str.charAt(i);
if(chr<48 || chr>57)
return false;
}
}
return true;
}
private int stonum(String str)
{
int num=0;
if(str.charAt(0)=='-')
{
for(int i=str.length()-1;i>0;i--)
{
int tmp=str.charAt(i)-48;
for(int j=str.length()-1-i;j>0;j--)
{
tmp=tmp*10;
}
num=num+tmp;
}
num=0-num;
}
else
{
for(int i=str.length()-1;i>=0;i--)
{
int tmp=str.charAt(i)-48;
for(int j=str.length()-1-i;j>0;j--)
{
tmp=tmp*10;
}
num=num+tmp;
}
}
return num;
}
}