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;
    }
};
相关推荐
zyx没烦恼1 分钟前
五种IO模型
开发语言·c++
syzyc36 分钟前
[ABC267F] Exactly K Steps
数据结构·动态规划·题解
EutoCool42 分钟前
Qt窗口:菜单栏
开发语言·c++·嵌入式硬件·qt·前端框架
Owen_Q2 小时前
Leetcode百题斩-二分搜索
算法·leetcode·职场和发展
zstar-_2 小时前
Claude code在Windows上的配置流程
笔记·算法·leetcode
圆头猫爹3 小时前
第34次CCF-CSP认证第4题,货物调度
c++·算法·动态规划
十五年专注C++开发3 小时前
hiredis: 一个轻量级、高性能的 C 语言 Redis 客户端库
开发语言·数据库·c++·redis·缓存
hi0_63 小时前
03 数组 VS 链表
java·数据结构·c++·笔记·算法·链表
碧海蓝天20224 小时前
C++法则21:避免将#include放在命名空间内部。
开发语言·c++
CodeWithMe4 小时前
【读书笔记】《C++ Software Design》第一章《The Art of Software Design》
开发语言·c++