C++ | Leetcode C++题解之第224题计算计算器

题目:

题解:

cpp 复制代码
class Solution {
public:
    int calculate(string s) {
        stack<int> ops;
        ops.push(1);
        int sign = 1;

        int ret = 0;
        int n = s.length();
        int i = 0;
        while (i < n) {
            if (s[i] == ' ') {
                i++;
            } else if (s[i] == '+') {
                sign = ops.top();
                i++;
            } else if (s[i] == '-') {
                sign = -ops.top();
                i++;
            } else if (s[i] == '(') {
                ops.push(sign);
                i++;
            } else if (s[i] == ')') {
                ops.pop();
                i++;
            } else {
                long num = 0;
                while (i < n && s[i] >= '0' && s[i] <= '9') {
                    num = num * 10 + s[i] - '0';
                    i++;
                }
                ret += sign * num;
            }
        }
        return ret;
    }
};
相关推荐
Mr_WangAndy2 分钟前
C++设计模式_行为型模式_责任链模式Chain of Responsibility
c++·设计模式·责任链模式·行为型模式
时间之里32 分钟前
【c++】:Lambda 表达式介绍和使用
开发语言·c++
坚持编程的菜鸟1 小时前
LeetCode每日一题——螺旋矩阵
c语言·算法·leetcode·矩阵
汉克老师1 小时前
GESP2025年9月认证C++四级( 第三部分编程题(1)排兵布阵)
c++·算法·gesp4级·gesp四级
(●—●)橘子……1 小时前
记力扣2009:使数组连续的最少操作数 练习理解
数据结构·python·算法·leetcode
GalaxyPokemon1 小时前
LeetCode - 1171.
算法·leetcode·链表
iナナ1 小时前
Java优选算法——位运算
java·数据结构·算法·leetcode
·心猿意码·2 小时前
C++智能指针解析
开发语言·c++
Han.miracle2 小时前
数据结构二叉树——层序遍历&& 扩展二叉树的左视图
java·数据结构·算法·leetcode
property-3 小时前
C++中#define和const的区别
开发语言·c++