Leetcode 227.基本计算器II

基本计算器II

实现一个基本的计算器来计算一个简单的字符串表达式的值。

字符串表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格  。 整数除法仅保留整数部分。

示例 1:

输入: "3+2*2"

输出: 7

示例 2:

输入: " 3/2 "

输出: 1

示例 3:

输入: " 3+5 / 2 "

输出: 5

说明:

  • 你可以假设所给定的表达式都是有效的。
  • 不要使用内置的库函数 eval。
 1 class Solution {
 2     public int calculate(String s) {
 3         int result=0,len=s.length(),num=0;
 4         char op='+';  //初始上一个运算符为加法 上个数字为0
 5         Stack<Integer> stack=new Stack<Integer>();
 6         for(int i=0;i<len;i++){
 7             char c=s.charAt(i);
 8             if(c>='0'){
 9                 num=num*10+s.charAt(i)-'0';
10             }
11             if(c<'0'&&c!=' '||i==len-1){
12                 if(op=='+') stack.push(num);
13                 if(op=='-') stack.push(-num);
14                 if(op=='*'||op=='/'){
15                     int temp=(op=='*')?stack.pop()*num:stack.pop()/num;
16                     stack.push(temp);
17                 }
18                 op=s.charAt(i);
19                 num=0;
20             }
21         }
22         while(!stack.isEmpty()){
23             result+=stack.pop();
24         }
25         return result;
26     }
27 }
原文地址:https://www.cnblogs.com/kexinxin/p/10203078.html