Evaluate Reverse Polish Notation
题目地址:
https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
这个题目咋看起来不难,其实要注意的点还是挺多的= =。
第一:主要考的应该是栈的应用,这还好。
第二:判断字符串是否为数字。
这个有许多需要注意的地方,比如是负数怎么判断?
第三:由于栈是先进后出,稍不注意会在除法那儿出现除0错误
ASCII的48~57是数字字符。这个应该记住...我是用这个来判断是否为数字的。
1 import java.util.Stack; 2 public class Solution { 3 public int evalRPN(String[] tokens) { 4 Stack<Integer> ex=new Stack<Integer>(); 5 for(String i:tokens) 6 { 7 if(isNum(i)) 8 { 9 ex.push(stonum(i)); 10 } 11 else 12 { 13 int first =ex.pop(); 14 int last=ex.pop(); 15 switch(i) 16 { 17 case "+": 18 ex.push(last+first); 19 break; 20 case "/": 21 ex.push(last/first); 22 break; 23 case "*": 24 ex.push(last*first); 25 break; 26 case "-": 27 ex.push(last-first); 28 break; 29 default: 30 break; 31 } 32 } 33 } 34 return ex.pop(); 35 36 } 37 private boolean isNum(String str) 38 { 39 if(str.charAt(0)=='-'&&str.length()>1) 40 { 41 return true; 42 } 43 else 44 { 45 for(int i=str.length();--i>=0;) 46 { 47 int chr=str.charAt(i); 48 if(chr<48 || chr>57) 49 return false; 50 } 51 } 52 return true; 53 } 54 private int stonum(String str) 55 { 56 int num=0; 57 if(str.charAt(0)=='-') 58 { 59 for(int i=str.length()-1;i>0;i--) 60 { 61 int tmp=str.charAt(i)-48; 62 for(int j=str.length()-1-i;j>0;j--) 63 { 64 tmp=tmp*10; 65 } 66 num=num+tmp; 67 } 68 num=0-num; 69 } 70 else 71 { 72 for(int i=str.length()-1;i>=0;i--) 73 { 74 int tmp=str.charAt(i)-48; 75 for(int j=str.length()-1-i;j>0;j--) 76 { 77 tmp=tmp*10; 78 } 79 num=num+tmp; 80 } 81 } 82 return num; 83 }