Basic Calculator II

这道题虽然是stack类型的题,但是因为这里写的方法并没有用额外空间,而且我个人也更觉得计算器类型的题比较像模拟算法,毕竟是真实存在的东西的行动模拟,这里没有拿自己的方法因为调用了stack而且逻辑不是很简洁,下面的方法实际上是把加减号的运算变成了和乘除法的特例(即乘一或乘负一)来进行的,然后利用curVal和preVal两个变量来实现对结果立即就地进行运算而不用储存,反正就是背板

class Solution(object):
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0

        s = s.strip().replace(' ', '')       # 这样可以剥掉字符所有的空
        n = len(s)
        res = 0
        preVal = 0
        sign = '+'
        i = 0

        while i < n:
            curVal = 0
            while i < n and 48 <= ord(s[i]) <= 57:
                curVal = curVal * 10 + ord(s[i]) - ord('0')
                i += 1
            if sign == '+':
                res += preVal
                preVal = curVal
            elif sign == '-':
                res += preVal
                preVal = -1 * curVal
            elif sign == '*':
                preVal = preVal * curVal
            elif sign == '/':
                preVal = int(float(preVal) / float(curVal))       # 这里要注意Python的带负数的除法结果很诡异

            if i < n:
                sign = s[i]
                i += 1

        res += preVal
        return res

results matching ""

    No results matching ""