leetcode 227. basic calculator 计算字符串表达式的值 python

227. Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
分析:

整体思路是处理 * 、/ 再处理 + 、- ,此外,注意在python中 -3 // 2 = -2 与实际的计算是有1的区别,这个题在搜狗面试中遇到

# coding=utf-8
class Solution(object):
    def calculate(self, string):
        if not string:
            return '0'
        stack, num, sign = [], 0, '+'
        for i in range(0, len(string)):
            if string[i].isdigit():
                num = num * 10 + int(string[i])  # 如果是连续的数字,得每次乘10
            #  i == len(string) - 1也要考虑,因为字符串末尾有许多空格情况也要考虑
            if not string[i].isdigit() and not string[i].isspace() or i == len(string) - 1:
                if sign == '+':
                    stack.append(num)
                elif sign == '-':
                    stack.append(-num)
                elif sign == '*':
                    stack.append(stack.pop() * num)
                else:
                    temp = stack.pop()
                    assert num != 0
                    if temp // num < 0 and temp % num != 0:
                        stack.append(temp // num + 1)  # 负数除的情况
                    else:
                        stack.append(temp // num)
                sign = string[i]
                num = 0
        return sum(stack)




猜你喜欢

转载自blog.csdn.net/banana1006034246/article/details/77868298