Basic Calculator

Problem: Basic Calculator

If we ignore parentheses, we can just store current calculation result and look at the next number and judge whether it's positive or not. By this way, we can accumulate all numbers together as different positive or negative numbers to do calculation. We can consider parentheses as beginning of a new calculation thus use recursion to solve it.

Code in Python:

class Solution(object):
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        s = list(s + ")")
        s.reverse()
        return self._calculate(s)

    def _calculate(self, s):
        ans, cur, pos = 0, 0, 1
        c = s.pop()
        while c != ")":
            if c == " ":
                c = s.pop()
                continue
            if c in string.digits:
                cur = cur * 10 + int(c)
            elif c == "(":
                ans += pos * self._calculate(s)
            else:
                ans += pos * cur
                cur = 0
                if c == "+":
                    pos = 1
                elif c == "-":
                    pos = -1
            c = s.pop()
        ans += pos * cur

        return ans

In this piece of code, we add a close parenthesis to mark end of current calculation. We reverse the string and pop character from it to access one character each a time.

results matching ""

    No results matching ""