Monday, September 18, 2017

227. Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
Note: Do not use the eval built-in library function.

Solution:
It is easier than Basic calculator, because there are no parenthesis involved at all so it is more predictable. Whenever we get a number we check the previous operator, if the previous operator is '*' or '/' we do the math with previous number which is on the top of our stack. Otherwise if the previous operator is '+' or '-', we push the number with the sign to the stack. 
  public int calculate(String s) {  
     if(s==null || s.length()==0) return 0;  
     char preO='+';  
     Stack<Integer> st=new Stack<Integer>();  
     for(int i=0;i<s.length();i++){  
       char c=s.charAt(i);  
       if(Character.isDigit(c)){  
         int num=0;  
         while(i<s.length() && Character.isDigit(s.charAt(i))) num=num*10+s.charAt(i++)-'0';  
         i--;  
         if(preO=='+') st.push(num);  
         else if(preO=='-') st.push(-num);  
         else if(preO=='*') st.push(num*st.pop());  
         else st.push(st.pop()/num);  
       }  
       else if(c==' ') continue;  
       else preO=c;        
     }  
     int sum=0;  
     while(!st.empty()) sum+=st.pop();  
     return sum;  
   }  
Actually, the stack can be omitted with some variables and elegant thoughts. There are couple good solution in the discussion section of this problem @ leetcode 

No comments:

Post a Comment