evaluate

1.6k 词

Evaluate 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

java

java的stack中,s.pop()不仅会弹出栈顶元素,还会返回栈顶元素。

String转int
Integer.parseInt
Integer.valueof()返回的是Integer的对象。
Integer.valueof().intValue();返回的也是一个int的值。

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
import java.util.Stack;
public class {
public int evalRPN(String[] tokens) {
Stack<Integer> s=new Stack<Integer>();
int len=tokens.length;
if(len==0)
return 0;
for(int i=0;i<len;i++)
{
if(tokens[i].equals("+"))
{
int a=s.pop();
int b=s.pop();
s.push(a+b);
}
else if(tokens[i].equals("-"))
{
int a=s.pop();
int b=s.pop();
s.push(b-a);
}
else if(tokens[i].equals("*"))
{
int a=s.pop();
int b=s.pop();
s.push(a*b);
}
else if(tokens[i].equals("/"))
{
int a=s.pop();
int b=s.pop();
s.push(b/a);
}
else
{
int temp=Integer.parseInt(tokens[i]);
s.push(temp);
}
}
return s.peek();
}
}

C++

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
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> s;
int len=tokens.size();
if(len==0)
return 0;
for(int i=0;i<len;i++)
{
if(tokens[i]=="+")
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
s.push(a+b);
}
else if(tokens[i]=="-")
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
s.push(b-a);
}
else if(tokens[i]=="*")
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
s.push(a*b);
}
else if(tokens[i]=="/")
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
s.push(b/a);
}
else
{
s.push(stoi(tokens[i]));
}
}
return s.top();
}
};