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;
}
相关推荐
smj2302_796826525 分钟前
解决leetcode第3826题.最小分割分数问题
数据结构·python·算法·leetcode
VT.馒头18 分钟前
【力扣】2705. 精简对象
javascript·数据结构·算法·leetcode·职场和发展·typescript
元亓亓亓27 分钟前
LeetCode热题100--136. 只出现一次的数字--简单
算法·leetcode·职场和发展
小柯博客32 分钟前
从零开始打造 OpenSTLinux 6.6 Yocto 系统 - STM32MP2(基于STM32CubeMX)(六)
c语言·git·stm32·单片机·嵌入式硬件·开源·yocto
im_AMBER32 分钟前
Leetcode 113 合并 K 个升序链表
数据结构·学习·算法·leetcode·链表
TracyCoder1231 小时前
LeetCode Hot100(22/100)——141. 环形链表
算法·leetcode·链表
重生之后端学习1 小时前
146. LRU 缓存
java·数据结构·算法·leetcode·职场和发展
程曦曦1 小时前
原地删除有序数组重复项:双指针法的艺术与实现
数据结构·算法·leetcode
你怎么知道我是队长1 小时前
C语言---排序算法6---递归归并排序法
c语言·算法·排序算法
梵刹古音2 小时前
【C语言】 字符数组与多维数组
c语言·数据结构·算法