Basic Calculator II

Problem: Basic Calculator II

We use three steps to solve this problem. First we parse digits into numbers and clear spaces. Then we calculate all multiplication and division. At last, we calculate all addition and subtraction.

Code in Python:

class Solution:
    # @param {string} s
    # @return {integer}
    def calculate(self, s):
        first = []
        for c in s:
            if c == '0' or c == '1' or c == '2' or c == '3' or c == '4' or c == '5' or c == '6' or c == '7' or c == '8' or c == '9':
                if len(first) == 0:
                    first.append(int(c))
                elif isinstance(first[len(first)-1], int):
                    first.append(first.pop() * 10 + int(c))
                else:
                    first.append(int(c))
            elif c == ' ':
                continue
            else:
                first.append(c)

        second = []
        for i in range(len(first)):
            if first[i] == '*':
                second.append(second.pop() * first[i+1])
            elif first[i] == '/':
                second.append(second.pop() / first[i+1])
            elif i > 0 and (first[i-1] == '*' or first[i-1] == '/'):
                continue
            else:
                second.append(first[i])

        result = 0
        for i in range(len(second)):
            if second[i] == '+':
                result = result + second[i+1]
            elif second[i] == '-':
                result = result - second[i+1]
            elif i > 0 and (second[i-1] == '+' or second[i-1] == '-'):
                continue
            else:
                result = result + second[i]

        return result

results matching ""

    No results matching ""