[Leetcode] 772. Basic Calculator III 解题报告

实现一个基本计算器,评估简单表达式字符串。表达式包含非负整数、加减运算符、括号。遵循非负整数除法向零取整的规则。给定的表达式总是有效的。本文介绍了解题思路和代码实现,重点在于递归处理括号内的计算,并使用“引用传递”技巧处理全局变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -non-negative integers and empty spaces .

The expression string contains only non-negative integers, +-*/ operators , open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647].

Some examples:

"1 + 1" = 2
" 6-4 / 2 " = 4
"2*(5+5*2)/3+(6/2+8)" = 21
"(2+6* 3+5- (3*14/7+2)*5)+3"=-12

 Note: Do not use the eval built-in library function.

思路

我们顺序循环,处理字符串中的各个字符:如果遇到‘+’或者‘-’,就将其加入到数组nums中;如果遇到‘*’或者‘/’,则直接进行计算;如果遇到'(',则递归调用parseExpr函数,返回括号对里面的计算结果。当所有的数都计算完毕之后,将数组nums中的所有数加起来,返回和就可以了。

这里的奥妙在于采用"pass by reference"的方法,使得i成为“全局变量”;另外就是合理地设计递归调用的函数,以处理括号嵌套的问题。

代码

class Solution {
public:
    int calculate(string s) {
        int i = 0;
        return parseExpr(s, i);
    }
private:
    int parseExpr(string &s, int &i) {  // parse the expression
        vector<int> nums;
        char op = '+';
        int n;
        for (; i < s.length() && op != ')'; ++i) {
            if (s[i] == ' ') {
                continue;
            }
            if (s[i] == '(') {
                n = parseExpr(s, ++i);
            }
            else {
                n = parseNum(s, i);
            }
            switch(op) {
                case '+':
                    nums.push_back(n);
                    break;
                case '-':
                    nums.push_back(-n);
                    break;
                case '*':
                    nums.back() *= n;
                    break;
                case '/':
                    nums.back() /= n;
                    break;
            }
            op = s[i];
        }
        int res = 0;
        for (int n : nums) {
            res += n;
        }
        return res;
    }
    
    int parseNum(string &s, int &i) {       // parse the num
        int n = 0;
        while (i < s.length() && isdigit(s[i])) {
            n = 10 * n + s[i++] - '0';
        }
        return n;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值