美文网首页
Leetcode227. Basic Calculator II

Leetcode227. Basic Calculator II

作者: Persistence2 | 来源:发表于2017-02-23 00:12 被阅读3次

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

思路

  • 拿到第一个数
  • 拿到第一个操作符
  • 拿到第二个数
  • 根据操作符类型进行判断。如果是乘除对num进行更新,如果是加减,对最终结果res进行更新,并更新运算符。
  • 判断最后一个运算符,如果是加减更新res
public class Solution {
    public int calculate(String s) {
        int res = 0, num = 0;
        int index = 0;
        char symbol = '+';
        int len = s.length();
        
        while(index < len && s.charAt(index) == ' ' ) {
            index++;
        }
        while(index < len && isDigit(s.charAt(index))) {
            num = num * 10 + (s.charAt(index++) - '0');
        }
        while(index < len){

            if (index < len && s.charAt(index) == ' ' ) {
                index++;
                continue;
            }
            char symbol1 = s.charAt(index++);
            int tmp = 0;
            while(index < len && s.charAt(index) == ' ' ) {
                index++;
            }
            while(index < len && isDigit(s.charAt(index))) {
                tmp = tmp * 10 + (s.charAt(index++) - '0');
            }

            if (symbol1 == '+' || symbol1 == '-') {
                if (symbol == '+'){
                    res += num;
                }else {
                    res -= num;
                }
                num = tmp;
                symbol = symbol1;
            } else {
                if (symbol1 == '*') {
                    num *= tmp;
                } else {
                    num /= tmp;
                }
            }
        }

        if (symbol == '+') {
            res += num;
        } else {
            res -= num;
        }
        return res;
        
    }

    private final boolean isDigit(char s) {
        return s >= '0' && s <= '9';
    }
} 

相关文章

网友评论

      本文标题:Leetcode227. Basic Calculator II

      本文链接:https://www.haomeiwen.com/subject/survwttx.html