leetcode--evaluate-reverse-polish-notation
2017-06-30 15:23
447 查看
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:
分析:逆波兰表达式的计算;
建立一个栈,将每个数字压入栈,当遇到计算符事,弹出前两个数参与计算,并把结果压栈
import java.util.*;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stackNum=new Stack<>();
int len=tokens.length;
for(int i=0;i<len;i++){
try{
stackNum.push(Integer.parseInt(tokens[i]));
}catch(Exception e){
String operation=tokens[i];
int numA=stackNum.pop();
int numB=stackNum.pop();
switch(operation){
case "+":
stackNum.push(numB+numA);
break;
case "-":
stackNum.push(numB-numA);
break;
case "*":
stackNum.push(numB*numA);
break;
case "/":
stackNum.push(numB/numA);
break;
}
}
}
return stackNum.pop();
}
}
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.*;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stackNum=new Stack<>();
int len=tokens.length;
for(int i=0;i<len;i++){
try{
stackNum.push(Integer.parseInt(tokens[i]));
}catch(Exception e){
String operation=tokens[i];
int numA=stackNum.pop();
int numB=stackNum.pop();
switch(operation){
case "+":
stackNum.push(numB+numA);
break;
case "-":
stackNum.push(numB-numA);
break;
case "*":
stackNum.push(numB*numA);
break;
case "/":
stackNum.push(numB/numA);
break;
}
}
}
return stackNum.pop();
}
}
相关文章推荐
- leetcode第一刷_Evaluate Reverse Polish Notation
- 【LeetCode】150. Evaluate Reverse Polish Notation
- 【LeetCode-面试算法经典-Java实现】【151-Evaluate Reverse Polish Notation(计算逆波兰式)】
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode - Evaluate Reverse Polish Notation
- [LeetCode]Evaluate Reverse Polish Notation
- 【LeetCode】-Evaluate Reverse Polish Notation
- LeetCode Evaluate Reverse Polish Notation
- 【LeetCode】Evaluate Reverse Polish Notation
- leetcode-Evaluate Reverse Polish Notation
- leetcode Evaluate Reverse Polish Notation
- [LeetCode]Evaluate Reverse Polish Notation
- 【LeetCode】150. Evaluate Reverse Polish Notation
- (leetcode)Evaluate Reverse Polish Notation
- LeetCode(150) Evaluate Reverse Polish Notation
- evaluate-reverse-polish-notation(Leetcode)
- leetcode evaluate-reverse-polish-notation
- LeetCode——150. Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation——LeetCode
- Leetcode Evaluate Reverse Polish Notation