LeetCode227. 基本计算器 II

题目

基本计算器 II
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

整数除法仅保留整数部分。

示例 1:

输入:s = “3+2*2”
输出:7
示例 2:

输入:s = " 3/2 "
输出:1
示例 3:

输入:s = " 3+5 / 2 "
输出:5

提示:

1 <= s.length <= 3 * 105
s 由整数和算符 (’+’, ‘-’, ‘*’, ‘/’) 组成,中间由一些空格隔开
s 表示一个 有效表达式
表达式中的所有整数都是非负整数,且在范围 [0, 231 - 1] 内
题目数据保证答案是一个 32-bit 整数

代码

先处理字符串里面的空格,如果有空格,则跳过,如果字符串里面的是数字则将数字存到num变量,当操作符为‘±’则将数字入栈,当操作符为‘*/’则将数字运算完再入栈。最后统计整个栈的数字之和。

class Solution:
    def calculate(self, s: str) -> int:
        size = len(s)
        stack = []
        index = 0
        op='+'
        while index<size:
            if s[index]==' ':
                index+=1
                continue
            if s[index].isdigit():
                num=ord(s[index])-ord('0')
                while index+1<size and s[index+1].isdigit():
                    index+=1
                    num=num*10+ord(s[index])-ord('0')
                if op=='+':
                    stack.append(num)
                elif op=='-':
                    stack.append(-num)
                elif op=='*':
                    top=stack.pop()
                    num=num*top
                    stack.append(num)
                elif op=='/':
                    top=stack.pop()
                    num=int(top/num)
                    stack.append(num)
            elif s[index] in '+-*/':
                op = s[index]
            index+=1
        return sum(stack)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

isasiky

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值