LeetCode 面试题 16.26. 计算器

题目描述

面试题 16.26. 计算器

思路分析

解法一:单次扫描(推荐)

核心思路

  • 维护当前数字 num、上一段结果 last 与累计结果 result
  • 遇到运算符时,根据上一个运算符更新 last 或合并到 result
  • 扫描结束后返回 result + last,即可覆盖乘除优先级。


复杂度分析

  • 时间复杂度:O(n),其中 n 表示字符串长度。
  • 空间复杂度:O(1),仅使用常数额外空间。
class Solution {
    public int calculate(String s) {
        int result = 0;
        int last = 0;
        int num = 0;
        char sign = '+';

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                num = num * 10 + (c - '0');
            }

            if ((c < '0' || c > '9') && c != ' ' || i == s.length() - 1) {
                if (sign == '+') {
                    result += last;
                    last = num;
                } else if (sign == '-') {
                    result += last;
                    last = -num;
                } else if (sign == '*') {
                    last = last * num;
                } else if (sign == '/') {
                    last = last / num;
                }

                sign = c;
                num = 0;
            }
        }

        return result + last;
    }
}
func calculate(s string) int {
	result := 0
	last := 0
	num := 0
	sign := byte('+')

	for i := 0; i < len(s); i++ {
		c := s[i]
		if c >= '0' && c <= '9' {
			num = num*10 + int(c-'0')
		}

		if (c < '0' || c > '9') && c != ' ' || i == len(s)-1 {
			if sign == '+' {
				result += last
				last = num
			} else if sign == '-' {
				result += last
				last = -num
			} else if sign == '*' {
				last = last * num
			} else if sign == '/' {
				last = last / num
			}

			sign = c
			num = 0
		}
	}

	return result + last
}

相似题目

题目 难度 考察点
224. 基本计算器 困难
227. 基本计算器 II 中等 单次扫描
772. 基本计算器 III 困难 递归/栈
150. 逆波兰表达式求值 中等
394. 字符串解码 中等
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/70406468
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!