Leetcode227. 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

思路

  • 拿到第一个数
  • 拿到第一个操作符
  • 拿到第二个数
  • 根据操作符类型进行判断。如果是乘除对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';
    }
} 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • FreeCodeCamp - Basic JavaScript 写在前面: 我曾经在进谷前刷过这一套题,不过当时只...
    付林恒阅读 16,521评论 5 28
  • 爱和感恩,应该是所有物种能够延续的必要条件吧。 突然想起这个话题。是因为最近遇见的一些人,一些事。 等等,如果我把...
    香杉阅读 220评论 1 1
  • 大多数习惯性低落、沮丧、躁郁的人,都有一个共通的毛病:“痛苦回忆反刍症”。明明今天过得好好的,顺风顺水,天晴日丽,...
    岚风的叶子阅读 1,499评论 1 0