Leetcode 150. Evaluate Reverse Polish Notation || Code + Explanation + Example Walkthrough

preview_player
Показать описание
Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, and /. Each operand may be an integer or another expression.

Note that division between two integers should truncate toward zero.

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.



Example 1:

Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:

Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:

Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((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

Рекомендации по теме
Комментарии
Автор

very nice explanation you deserve more than this 🙏🙏🙏

abaytekle
Автор

Superb Explanation👌.Neat and clean. You deserves this

venkatakalyan
Автор

Thank you soo much in a single attempt i have done this.Thanks soo much

KRajesh-ejdy
Автор

Use "long long int" instead of "int" those who are getting RUNTIME ERROR

shubhamsukum
Автор

terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi err is showing

anujkanojia
Автор

Nice explanation but its saying wrong answer for test case 2: ["4", "13", "5", "/", "+"]. My answer is 15 but expected is 6

none
Автор

i am doing this code in java and it is giving an empty stack exception I have added the code below please help

class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> st=new Stack<Integer>();
if(tokens.length==0)
return 0;
for(String s:tokens)
{
if(s.equals("+"))
{
int a=st.peek();
st.pop();
int b=st.peek();
st.pop();
st.push(a+b);
}
else if(s.equals("-"))
{
int a=st.peek();
st.pop();
int b=st.peek();
st.pop();
st.push(a-b);
}
else if(s.equals("*"))
{
int a=st.peek();
st.pop();
int b=st.peek();
st.pop();
st.push(a*b);
}
else if(s.equals("/"))
{
int a=st.peek();
st.pop();
int b=st.peek();
st.pop();
if(a>b &&b!=0)
st.push(a/b);
else if(b>a && a!=0)st.push(b/a);
}
else
{
int a=Integer.parseInt(s);
st.push(a);
}
}
return st.pop();
}
}

Star_Bawa
welcome to shbcf.ru