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;
    }
};
相关推荐
天若有情6736 小时前
【c++】手撸C++ Promise:从零实现通用异步回调组件,支持链式调用+异常安全
开发语言·前端·javascript·c++·promise
学困昇6 小时前
C++中的异常
android·java·c++
sin_hielo7 小时前
leetcode 2435
数据结构·算法·leetcode
合作小小程序员小小店7 小时前
桌面安全开发,桌面二进制%恶意行为拦截查杀%系统安全开发3.0,基于c/c++语言,mfc,win32,ring3,dll,hook,inject,无数据库
c语言·开发语言·c++·安全·系统安全
Codeking__7 小时前
C++ 11 atomic 原子性操作
开发语言·c++
crescent_悦7 小时前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法
卡提西亚8 小时前
C++笔记-34-map/multimap容器
开发语言·c++·笔记
2***B4498 小时前
C++在金融中的QuantLibXL
开发语言·c++·金融
A***07178 小时前
C++在游戏中的阴影渲染
开发语言·c++·游戏
Q***l6879 小时前
C++在计算机图形学中的渲染
开发语言·c++