227. Basic Calculator II

class Solution{

    public int calculate(String s) {
     
     Stack<Integer> stack=new Stack<>();
     int res=0;
     int num=0;
     int i=0;
     char op='+';
      while(i<s.length())
      {

        if(s.charAt(i)>='0')
        {
        	num=num*10+s.charAt(i)-'0';
        }

        if(s.charAt(i)<'0'&&s.charAt(i)!=' '||i==s.length()-1)
        {
        	if(op=='+')
        		stack.push(num);
        	if(op=='-')
        		stack.push(num*(-1));
        	if (op=='*'||op=='/') {
        		
        		int tmp=(op=='*')? stack.peek()*num:stack.peek()/num;
        		stack.pop();
        		stack.push(tmp);
        	}

        	op=s.charAt(i);
        	num=0;
        }
          i++;
      }

      while(!stack.isEmpty())
      {

      	res=res+stack.peek();
      	stack.pop();
      }

      return res;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章