python solution without stack O(n) & O(1) space


  • 0

    class Solution(object):
    def calculate(self, s):
    """
    :type s: str
    :rtype: int
    """
    ret, last_value, cur_value, cur_op = 0, 0, 0, '+'

        for i, ch in enumerate(s): 
            if ch.isdigit(): 
                cur_value = cur_value * 10 + ord(ch) - ord('0')
            if (not ch.isdigit() and ch != ' ') or i == len(s)-1: 
                if cur_op == '+': 
                    ret, last_value = ret+cur_value, cur_value 
                elif cur_op == '-':
                    ret, last_value = ret-cur_value, -cur_value
                elif cur_op == '*': 
                    ret, last_value = ret-last_value + last_value*cur_value, last_value*cur_value
                else: 
                    ret, last_value, add  = ret-last_value + last_value // cur_value,  last_value // cur_value, (last_value % cur_value != 0)
                    if last_value < 0 : ret, last_value = ret + add, last_value + add
                cur_value, cur_op = 0, ch
                    
        return ret

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.