友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

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.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

  • You may assume that the given expression is always valid.

  • Do not use the eval built-in library function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * Runtime: 5 ms, faster than 98.92% of Java online submissions for Basic Calculator II.
 *
 * Memory Usage: 42.8 MB, less than 5.97% of Java online submissions for Basic Calculator II.
 *
 * Copy from: https://leetcode.com/problems/basic-calculator-ii/discuss/62996/Java-straight-forward-iteration-Solution-with-comments-No-Stack-O(N)-and-O(1)[Java straight forward iteration Solution with comments, No Stack, O(N) & O(1) - LeetCode Discuss]
 */
public int calculate(String s) {
    if (Objects.isNull(s) || s.length() == 0) {
        return 0;
    }
    int result = 0;
    long previous = 0;
    char operator = '+';

    int length = s.length();

    for (int i = 0; i < length; i++) {
        char c = s.charAt(i);
        if (c == ' ') {
            continue;
        }
        if (Character.isDigit(c)) {
            int value = c - '0';
            while (i + 1 < length && Character.isDigit(s.charAt(i + 1))) {
                value = value * 10 + (s.charAt(i + 1) - '0');
                i++;
            }
            if (operator == '+') {
                result += previous;
                previous = value;
            } else if (operator == '-') {
                result += previous;
                previous = -value;
            } else if (operator == '*') {
                previous *= value;
            } else if (operator == '/') {
                previous /= value;
            }
        } else {
            operator = c;
        }
    }
    result += previous;
    return result;
}