文章目录
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).