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;
}
相关推荐
-qOVOp-9 分钟前
408第一季 - 数据结构 - 排序II
数据结构·算法·排序算法
小胖同学~11 分钟前
快速入门数据结构--栈
算法
C++ 老炮儿的技术栈12 分钟前
VSCode -配置为中文界面
大数据·c语言·c++·ide·vscode·算法·编辑器
刃神太酷啦33 分钟前
聚焦 string:C++ 文本处理的核心利器--《Hello C++ Wrold!》(10)--(C/C++)
java·c语言·c++·qt·算法·leetcode·github
CoovallyAIHub34 分钟前
云南电网实战:YOLOv8m改进模型攻克输电线路异物检测难题技术详解
深度学习·算法·计算机视觉
蜗牛的旷野40 分钟前
华为OD机试_2025 B卷_磁盘容量排序(Python,100分)(附详细解题思路)
python·算法·华为od
Sun_light1 小时前
链表 --- 高效离散存储的线性数据结构
前端·javascript·算法
西西弗Sisyphus1 小时前
低秩分解的本质是通过基矩阵和系数矩阵的线性组合,以最小的存储和计算代价近似表示复杂矩阵
线性代数·算法·矩阵
物联网嵌入式小冉学长2 小时前
10.C S编程错误分析
c语言·stm32·单片机·算法·嵌入式
王中阳Go18 小时前
从超市收银到航空调度:贪心算法如何破解生活中的最优决策谜题?
java·后端·算法