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;
}
相关推荐
AndrewHZ8 小时前
【图像处理基石】如何高质量地生成一张庆祝元旦的图片?
图像处理·人工智能·opencv·算法·计算机视觉·生成式模型·genai
光明西道45号8 小时前
Leetcode 15. 三数之和
数据结构·算法·leetcode
一路往蓝-Anbo8 小时前
C语言从句柄到对象 (四) —— 接口抽象:从 Switch-Case 到通用接口
c语言·开发语言·stm32·嵌入式硬件
还不秃顶的计科生8 小时前
LeetCode 热题 100第一题:两数之和python版本
python·算法·leetcode
Swift社区9 小时前
LeetCode 462 - 最小操作次数使数组元素相等 II
算法·leetcode·职场和发展
nike0good9 小时前
Goodbye 2025 题解
开发语言·c++·算法
崇山峻岭之间9 小时前
Matlab学习记录19
学习·算法·matlab
jllllyuz9 小时前
基于帧差法与ViBe算法的MATLAB前景提取
开发语言·算法·matlab
wen__xvn9 小时前
代码随想录算法训练营DAY1第一章 数组part01
数据结构·算法·leetcode
爱编码的傅同学9 小时前
【程序地址空间】页表的映射方式
c语言·数据结构·c++·算法