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;
}
相关推荐
xlp666hub9 小时前
Leetcode第五题:用C++解决盛最多水的容器问题
linux·c++·leetcode
xlp666hub1 天前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
xlp666hub1 天前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
xlp666hub2 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
RuoZoe7 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_10 天前
C语言内存函数
c语言·后端
norlan_jame12 天前
C-PHY与D-PHY差异
c语言·开发语言
琢磨先生David12 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
czy878747512 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_5312371712 天前
C语言-数组练习进阶
c语言·开发语言·算法