Leetcode 227 Solution

This article provides solution to leetcode question 227 (basic-calculator-ii)

https://leetcode.com/problems/basic-calculator-ii

Solution

class Solution:
    def calculate(self, s: str) -> int:
        s = str.replace(s, ' ', '') + '+0'
        if s[0] != '+' or s[0] != '-':
            s = '+' + s

        last_op = '+'
        last_num = 0

        nums = []
        ops = []

        for ch in s:
            if '0' <= ch <= '9':
                last_num = last_num * 10 + int(ch)
            elif ch == '+' or ch == '-' or ch == '*' or ch == '/':
                if last_op == '+' or last_op == '-':
                    nums.append(last_num)
                    ops.append(last_op)
                elif last_op == '*':
                    nums[-1] *= last_num
                elif last_op == '/':
                    nums[-1] //= last_num

                last_op = ch
                last_num = 0

        ans = 0
        for num, op in zip(nums, ops):
            if op == '+':
                ans += num
            elif op == '-':
                ans -= num
        return ans