题解 | #牛牛计算器#

牛牛计算器

https://www.nowcoder.com/practice/192ac31d5e054abcaa10b72d9b01cace

考察的知识点:栈的基本操作;

解答方法分析:

  1. 创建一个整数类型的栈 nums,用于存储计算结果或中间结果。
  2. 定义一个整数变量 num,用于存储当前数字的值。
  3. 定义一个字符变量 op,用于存储当前操作符。
  4. 遍历输入的字符串 s,对每个字符进行。如果当前字符是数字,则将其与 num 相乘并更新 num 的值。如果当前字符是左括号 ( 则找到与之匹配的右括号 ) 的位置,并将括号内的子字符串作为新的表达式计算结果,并更新 num 的值。如果当前不为空格,或者已经遍历到字符串末尾,则进行计算。根据上一个操作符 op 的值,分别执行加法、减法乘法操作。将计算结果存入栈 nums。将 num 重置为0,且将当前字符赋值给 op。
  5. 循环遍历栈 nums,将栈中的元素依次出栈并累加到结果变量 res 中。
  6. 返回结果变量 res。

所用编程语言:C++;

完整编程代码:↓

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @return int整型
     */
    int calculate(string s) {
        stack<int> nums;
        int num = 0;
        char op = '+';

        for (int i = 0; i < s.length(); i++) {
            char c = s[i];

            if (isdigit(c)) {
                num = num * 10 + (c - '0');
            } else if (c == '(') {
                int j = i, cnt = 0;

                for (; i < s.length(); i++) {
                    if (s[i] == '(') cnt++;
                    if (s[i] == ')') cnt--;
                    if (cnt == 0) {
                        break;
                    }
                }
                num = calculate(s.substr(j + 1, i - j - 1));
            }

            if (!isspace(c) || i == s.length() - 1) {
                if (op == '+') {
                    nums.push(num);
                } else if (op == '-') {
                    nums.push(-num);
                } else if (op == '*') {
                    int temp = nums.top() * num;
                    nums.pop();
                    nums.push(temp);
                }
                num = 0;
                op = c;
            }
        }
        int res = 0;
        while (!nums.empty()) {
            res += nums.top();
            nums.pop();
        }
        return res;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-24 13:40
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务