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;
}
相关推荐
橘子真甜~8 分钟前
C/C++ Linux网络编程5 - 网络IO模型与select解决客户端并发连接问题
linux·运维·服务器·c语言·开发语言·网络·c++
余俊晖43 分钟前
英伟达开源多模态视觉语言模型-Nemotron Nano V2 VL模型架构、训练方法、训练数据
人工智能·算法·语言模型·自然语言处理·多模态
2501_9411114643 分钟前
C++中的原型模式
开发语言·c++·算法
高洁0144 分钟前
国内外具身智能VLA模型深度解析(2)国外典型具身智能VLA架构
深度学习·算法·aigc·transformer·知识图谱
一只会写代码的猫1 小时前
C# 性能优化:从垃圾回收到多线程并发
jvm·算法
wangjialelele1 小时前
详解mysql命令行操作与语言链接
c语言·数据库·c++·mysql·oracle
学生小羊1 小时前
A. C05.L08.贪心算法入门
算法·贪心算法
AndrewHZ2 小时前
【图像处理基石】图像连通域计算:原理、算法实现与应用全解析
图像处理·算法·计算机视觉·cv·算法原理·视觉算法·连通域计算
Dev7z2 小时前
基于Matlab遗传算法与蚁群算法的风光储并网微电网容量优化研究
算法·matlab·蚁群算法·多能源微电网
一直在努力的小宁2 小时前
《代码随想录-精华内容提取》07 二叉树
数据结构·算法·链表·面试