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;
    }
};
相关推荐
样例过了就是过了9 分钟前
LeetCode热题100 最大子数组和
数据结构·算法·leetcode
wangluoqi13 分钟前
c++ 逆元 小总结
开发语言·c++
瓦特what?18 分钟前
插 入 排 序
开发语言·c++
『往事』&白驹过隙;28 分钟前
C/C++中的格式化输出与输入snprintf&sscanf
linux·c语言·c++·笔记·学习·iot·系统调用
Je1lyfish31 分钟前
CMU15-445 (2026 Spring) Project#1 - Buffer Pool Manager
linux·数据库·c++·后端·链表·课程设计·数据库架构
踩坑记录32 分钟前
leetcode hot100 200. 岛屿数量 medium dfs
leetcode·深度优先
zyeyeye1 小时前
自定义类型:结构体
c语言·开发语言·数据结构·c++·算法
俩娃妈教编程1 小时前
2023 年 03 月 二级真题(1)--画三角形
c++·算法·双层循环
航哥的女人1 小时前
C++文件操作
开发语言·c++
追随者永远是胜利者2 小时前
(LeetCode-Hot100)4. 寻找两个正序数组的中位数
java·算法·leetcode·职场和发展·go