根據逆波蘭表示法,求表達式的值。
有效的運算符包括 +, -, *, / 。每個運算對象可以是整數,也可以是另一個逆波蘭表達式。
說明:
整數除法只保留整數部分。
給定逆波蘭表達式總是有效的。換句話說,表達式總會得出有效數值且不存在除數爲 0 的情況。
示例 1:
輸入: [“2”, “1”, “+”, “3”, “*”]
輸出: 9
解釋: ((2 + 1) * 3) = 9
示例 2:
輸入: [“4”, “13”, “5”, “/”, “+”]
輸出: 6
解釋: (4 + (13 / 5)) = 6
示例 3:
輸入: [“10”, “6”, “9”, “3”, “+”, “-11”, “", “/”, "”, “17”, “+”, “5”, “+”]
輸出: 22
解釋:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
public class Solution
{
public int EvalRPN(string[] tokens)
{
if (tokens == null)
return 0;
Stack<int> temp = new Stack<int>();
for (int i = 0; i < tokens.Length; i++)
{
switch (tokens[i])
{
case "+":
int al = temp.Pop();
temp.Push(al+temp.Pop());
break;
case "-":
int bl = temp.Pop();
temp.Push(temp.Pop() - bl);
break;
case "*":
int cl = temp.Pop();
temp.Push(temp.Pop() * cl);
break;
case "/":
int dl = temp.Pop();
temp.Push(temp.Pop() / dl);
break;
default:
temp.Push(int.Parse(tokens[i]));
break;
}
}
return temp.Peek();
}
}
利用棧!