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 stack300000; - 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;
}
相关推荐
Lumos18641 分钟前
51单片机从零到实战(完结)——后续学习路线建议
算法
稚南城才子,乌衣巷风流1 小时前
DFS序详解:原理、应用与实现
算法·深度优先·图论
稚南城才子,乌衣巷风流1 小时前
动态树(Dynamic Tree)数据结构详解
数据结构·算法
爱刷碗的苏泓舒1 小时前
C 语言 if-else 与 switch-case 分支语句对比
c语言·开发语言
无相求码1 小时前
指针的5层境界,从入门到劝退:C语言指针进阶全解析
c语言
变量未定义~2 小时前
最小生成树1(Prim模板)、最小生成树2(kruskal模板)、最近公共祖先(模板)
算法
这就是佬们吗2 小时前
Python入门⑤-异常处理、文件操作与实战项目
开发语言·数据库·python·算法·pycharm
LONGZETECH2 小时前
新能源汽车充电设备装配与调试仿真教学软件 技术架构与核心实现解析
大数据·算法·3d·unity·架构·汽车
自学小白菜2 小时前
关于提升机器学习算法做预测回归任务精度的方法分享
算法·机器学习·回归·提升精度
C++ 老炮儿的技术栈2 小时前
基于MFC+原生GDI手动自绘仪表盘控件
c语言·c++·visual studio·控件·工业控制·gdi·自绘