LeetCode //C - 227. Basic Calculator II

227. Basic Calculator II

Given a string s which represents an expression, evaluate this expression and return its value.

The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [ − 2 31 , 2 31 − 1 ] [-2^{31}, 2^{31} - 1] [−231,231−1].

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Example 1:

Input: s = "3+2*2"
Output: 7

Example 2:

Input: s = " 3/2 "
Output: 1

Example 3:

Input: s = " 3+5 / 2 "
Output: 5

Constraints:
  • 1 <= s.length <= 3 * 1 0 5 10^5 105
  • s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.
  • s represents a valid expression.
  • All the integers in the expression are non-negative integers in the range [ 0 , 2 31 − 1 ] [0, 2^{31} - 1] [0,231−1].
  • The answer is guaranteed to fit in a 32-bit integer.

From: LeetCode

Link: 227. Basic Calculator II


Solution:

Ideas:
  • Stack Initialization: int stack[300000]; - We use a large array to simulate the stack.
  • Variables: int top = -1; - This variable keeps track of the top of the stack. int currentNumber = 0; - This stores the current number being processed.
  • Iteration through string: The loop iterates through each character in the string.
    • If a digit is found, it builds the currentNumber.
    • If a non-digit or end of string is found, the code processes the previous number with the current operation.
  • Operations Handling:
    • Based on the operation, the code either pushes the number onto the stack or performs multiplication/division and updates the stack.
  • Final Calculation: The loop sums all the values in the stack to get the final result.
Code:
c 复制代码
int calculate(char* s) {
    int stack[300000];
    int top = -1;
    int currentNumber = 0;
    char operation = '+';
    
    for (int i = 0; s[i] != '\0'; i++) {
        if (isdigit(s[i])) {
            currentNumber = currentNumber * 10 + (s[i] - '0');
        }
        if (!isdigit(s[i]) && !isspace(s[i]) || s[i + 1] == '\0') {
            if (operation == '+') {
                stack[++top] = currentNumber;
            } else if (operation == '-') {
                stack[++top] = -currentNumber;
            } else if (operation == '*') {
                stack[top] *= currentNumber;
            } else if (operation == '/') {
                stack[top] /= currentNumber;
            }
            operation = s[i];
            currentNumber = 0;
        }
    }
    
    int result = 0;
    for (int i = 0; i <= top; i++) {
        result += stack[i];
    }
    
    return result;
}
相关推荐
小懒懒6 分钟前
C语言典型例题58
c语言·开发语言·算法
YoLo-811 分钟前
《机器学习》周志华-CH5(神经网络)
c语言·神经网络·机器学习
鱼跃鹰飞23 分钟前
Leetcode面试经典150题-28.找出字符串第一个匹配项的下标
java·leetcode·面试
西农小陈1 小时前
python-禁止抽烟
开发语言·python·算法
马浩同学1 小时前
【GD32】RT-Thread实时操作系统移植(GD32F470ZGT6)
c语言·arm开发·单片机·嵌入式硬件·mcu
m0_743849653 小时前
LeetCode1732.找到最高海拔
开发语言·python·leetcode
攻城狮7号4 小时前
【3.5】贪心算法-解优势洗牌(类田忌赛马问题)
c++·算法·贪心算法
奋斗的小花生4 小时前
c-数据结构(顺序表、链表)
c语言·数据结构·链表
苦学数据结构7 小时前
25版王道数据结构课后习题详细分析 第五章 树与二叉树 5.3 二叉树的遍历和线索二叉树 选择题部分
数据结构·考研·算法
心.c9 小时前
【数据结构】二叉树基础(带你详细了解二叉树)
数据结构·c++·算法