-
Notifications
You must be signed in to change notification settings - Fork 0
/
150.evaluate-reverse-polish-notation.cs
53 lines (47 loc) · 1.42 KB
/
150.evaluate-reverse-polish-notation.cs
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
/*
* @lc app=leetcode id=150 lang=csharp
*
* [150] Evaluate Reverse Polish Notation
*/
// @lc code=start
public class Solution {
public int EvalRPN(string[] tokens) {
var numberStack = new Stack<int>();
foreach(var token in tokens){
if(token == "+"){
var right = numberStack.Pop();
var left = numberStack.Pop();
numberStack.Push(left + right);
} else if(token == "-"){
var right = numberStack.Pop();
var left = numberStack.Pop();
numberStack.Push(left - right);
} else if(token == "*"){
var right = numberStack.Pop();
var left = numberStack.Pop();
numberStack.Push(left * right);
} else if(token == "/") {
var right = numberStack.Pop();
var left = numberStack.Pop();
numberStack.Push(left / right);
} else {
numberStack.Push(getNumber(token));
}
}
return numberStack.Pop();
}
private int getNumber(string token){
int sign = 1;
int index = 0;
if(token[0] == '-'){
sign = -1;
index++;
}
int num = 0;
while(index < token.Length){
num = num * 10 + token[index++] - '0';
}
return sign * num;
}
}
// @lc code=end