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;
    }
};
相关推荐
白白白小纯7 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
小王C语言8 小时前
【7. 实现登录注册模块】:实现会话管理、注册/登录/退出 API
网络·c++
圣保罗的大教堂10 小时前
leetcode 3517. 最小回文排列 I 中等
leetcode
峥无11 小时前
C++11 深度详解:现代 C++ 基石全梳理
开发语言·c++·笔记
阿米亚波11 小时前
【C++ STL】std::unordered_multimap
开发语言·数据结构·c++·笔记·stl
小王C语言11 小时前
【3. 基于 Vibe Coding 的 OJ 平台】. 构建仓库、环境准备、需求梳理、安装依赖
网络·c++
小王C语言12 小时前
【8.进行接口测试】:通过 curl 进行接口自动化测试 / 通过 python 程序进行接口自动化测试
网络·c++
alphaTao12 小时前
LeetCode 每日一题 2026/7/27-2026/8/2
python·算法·leetcode
888CC++13 小时前
C++ 快速学习指南:从入门到进阶的实战路线
开发语言·c++
小小晓.13 小时前
C++记:函数
开发语言·c++·算法