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;
}
相关推荐
wuqingshun31415917 分钟前
蓝桥杯 11. 打印大X
数据结构·算法·职场和发展·蓝桥杯·深度优先
Blossom.1181 小时前
量子网络:构建未来通信的超高速“高速公路”
网络·opencv·算法·安全·机器学习·密码学·量子计算
A林玖1 小时前
【机器学习】朴素贝叶斯
人工智能·算法·机器学习
六边形战士DONK1 小时前
神经网络基础[损失函数,bp算法,梯度下降算法 ]
人工智能·神经网络·算法
wuqingshun3141592 小时前
蓝桥杯 2. 确定字符串是否是另一个的排列
数据结构·c++·算法·职场和发展·蓝桥杯
小刘|2 小时前
JVM 自动内存管理
java·jvm·算法
小羊不会c++吗(黑客小羊)2 小时前
c++头文件知识
算法
拓端研究室TRL2 小时前
PyMC+AI提示词贝叶斯项目反应IRT理论Rasch分析篮球比赛官方数据:球员能力与位置层级结构研究
大数据·人工智能·python·算法·机器学习
CoovallyAIHub3 小时前
Vision Transformers与卷积神经网络详细训练对比(附代码)
深度学习·算法·计算机视觉
地平线开发者3 小时前
征程 6 逆向自证hbm与bc一致性
算法·自动驾驶