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;
    }
};
相关推荐
June bug17 小时前
ISTQB CTFL基础级模拟卷C - 第四章(测试分析和设计)考点题目汇总
经验分享·职场和发展·学习方法
liu-yonggang17 小时前
ROS2 性能优化与功能增强方案
大数据·算法·性能优化
Alsian17 小时前
Day41 TensorBoard
人工智能·算法·机器学习
美好的事情能不能发生在我身上17 小时前
Leetcode热题100中的:矩阵专题
算法·leetcode·矩阵
Tisfy17 小时前
LeetCode 3296.移山所需的最少秒数:优先队列
算法·leetcode·题解·优先队列·模拟
㓗冽17 小时前
龟兔赛跑预测-进阶题6
算法
云泽80817 小时前
蓝桥杯算法精讲:贪心算法的简单应用与题解
算法·贪心算法·蓝桥杯
程序员夏末17 小时前
【LeetCode | 第四篇】算法笔记
笔记·算法·leetcode
DeepModel17 小时前
【概率分布】多项分布详解
算法·概率论
_日拱一卒17 小时前
LeetCode(力扣):只出现一次的数字
java·数据结构·算法