C语言 | Leetcode C语言题解之第227题基本计算题II

题目:

题解:

cpp 复制代码
int calculate(char* s) {
    int n = strlen(s);
    int stk[n], top = 0;
    char preSign = '+';
    int num = 0;
    for (int i = 0; i < n; ++i) {
        if (isdigit(s[i])) {
            num = num * 10 + (int)(s[i] - '0');
        }
        if (!isdigit(s[i]) && s[i] != ' ' || i == n - 1) {
            switch (preSign) {
                case '+':
                    stk[top++] = num;
                    break;
                case '-':
                    stk[top++] = -num;
                    break;
                case '*':
                    stk[top - 1] *= num;
                    break;
                default:
                    stk[top - 1] /= num;
            }
            preSign = s[i];
            num = 0;
        }
    }
    int ret = 0;
    for (int i = 0; i < top; i++) {
        ret += stk[i];
    }
    return ret;
}
相关推荐
☆璇2 小时前
【数据结构】排序
c语言·开发语言·数据结构·算法·排序算法
不讲废话的小白3 小时前
给 Excel 整列空格文字内容加上前缀:像给文字穿衣服一样简单!
c语言·excel
艾莉丝努力练剑5 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
珊瑚里的鱼10 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
不知道叫什么呀10 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc
秋说11 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
秋说13 小时前
【PTA数据结构 | C语言版】字符串插入操作(不限长)
c语言·数据结构·算法
凌肖战14 小时前
力扣网编程135题:分发糖果(贪心算法)
算法·leetcode
遇见尚硅谷15 小时前
C语言:20250714笔记
c语言·开发语言·数据结构·笔记·算法
Norvyn_716 小时前
LeetCode|Day11|557. 反转字符串中的单词 III|Python刷题笔记
笔记·python·leetcode