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;
    }
};
相关推荐
努力学习的小廉20 分钟前
【C++】 —— 笔试刷题day_23
开发语言·c++
whoarethenext29 分钟前
加密认证库openssl初始附带c/c++的使用源码
c语言·网络·c++·openssl
虾球xz1 小时前
游戏引擎学习第243天:异步纹理下载
c++·学习·游戏引擎
WaitWaitWait017 小时前
LeetCode每日一题4.20
算法·leetcode
蒟蒻小袁7 小时前
力扣面试150题--有效的括号和简化路径
算法·leetcode·面试
ptu小鹏8 小时前
类和对象(中)
开发语言·c++
明月看潮生10 小时前
青少年编程与数学 02-018 C++数据结构与算法 06课题、树
数据结构·c++·算法·青少年编程·编程与数学
小指纹10 小时前
动态规划(一)【背包】
c++·算法·动态规划
阳洞洞10 小时前
leetcode 二分查找应用
算法·leetcode·二分查找
zhaoyqcsdn11 小时前
抽象工厂模式及其在自动驾驶中的应用举例(c++代码实现)
c++·经验分享·笔记·设计模式