Leetcode 224. 基本计算器

文章目录

  • 题目
  • [代码(10.1 首刷看解析)](#代码(10.1 首刷看解析))

题目


Leetcode 224. 基本计算器

代码(10.1 首刷看解析)

cpp 复制代码
class Solution {
public:
    int calculate(string s) {
        stack<int> sk;  // 存储正负号
        sk.push(1);
        int sign = 1;
        int res = 0;
        int i = 0;
        while(i < s.size()) {
            if(s[i] == ' ') {
                i++;
            } else if(s[i] == '+') {
                sign = sk.top();
                i++;
            } else if(s[i] == '-') {
                sign = -sk.top();
                i++;
            } else if(s[i] == '(') {
                sk.push(sign);
                i++;
            } else if(s[i] == ')') {
                sk.pop();
                i++;
            } else {
                long long num = 0;
                while(i < s.size() && isdigit(s[i])) {
                    num = num*10+s[i]-'0';
                    i++;
                }
                res += num*sign;
            }
        }
        return res;
    }
};
相关推荐
随便发挥12 分钟前
Leetcode 剑指 Offer II 186. 文物朝代判断
leetcode
6Hzlia24 分钟前
【Classic 150 刷题计划】 LeetCode 205. 同构字符串 | C++ 双向绑定与哈希表映射
c++·算法·leetcode
有点。7 小时前
C++03阶段练习(练习题)
数据结构·算法·图论
周末也要写八哥8 小时前
经典算法实例:游戏中弱角色的数量(二)
算法
是Yu欸9 小时前
鸿蒙PC移植:2048 从网页小游戏到 AI 桌面应用
大数据·人工智能·算法·数据挖掘·openharmony·codex
鹿角片ljp9 小时前
KV Cache 解析
java·算法
liliangcsdn9 小时前
IVOL与偏度因子的对比测量分析
算法
threerocks10 小时前
Jev 入门第一课
算法
西柚研究生12345611 小时前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测
hetao173383712 小时前
2026-09-17 hetao1733837 的刷题记录
c++·算法