文章目录
try 1
result:答案正确:恭喜!您提交的程序通过了所有的测试用例
code:
import java.util.*;
public class Solution {
/**the program need a stack.
* Generally, we should convert a String tokens into a char[].
* But in this chanllenge,tokens is a "char[]",so we don't nee a char[].
* Besides,we should use Integer.paraseInt() to convert a char to int.
*if there an exception,it mean the char is a operators.
*/
public int evalRPN(String[] tokens) {
Stack<Integer> stack=new Stack<>();
for(int i=0;i<tokens.length;++i){
try {
Integer temp = Integer.parseInt(tokens[i]);
stack.push(temp);
}catch (NumberFormatException e){//mean tokens[i] is a operator
/*pop out two operand*/
Integer rightOperand=stack.pop();
Integer leftOperand=stack.pop();
if("+".equals(tokens[i])){
stack.push(leftOperand+rightOperand);
}else if("-".equals(tokens[i])){
stack.push(leftOperand-rightOperand);
}else if("*".equals(tokens[i])){
stack.push(leftOperand*rightOperand);
}else if("/".equals(tokens[i])){
stack.push(leftOperand/rightOperand);
}
}
}
return stack.pop();
}
}
Anylze:
Conclusion
Integer.parseInt()can convert String to int.And the function can throwsNumberFormatException(it is a unchecked exception).
本文深入探讨了解析逆波兰表示法(RPN)表达式的Java算法实现。文章详细介绍了如何使用栈数据结构来处理RPN表达式,通过Integer.parseInt()函数将字符转换为整数,并处理可能出现的NumberFormatException异常。此外,还提供了完整的代码示例和运行结果分析。
305

被折叠的 条评论
为什么被折叠?



