Transform * and / into + or - operator


  • 0
    X

    I use an interesting method which transform * and / into + and - operation. The basic idea is that if all the operators have same priority, then what we do is simple: calculate from left to right according to the operators. So I transform a+bc into a+0+x (say x = bc).

    def calculate(self, s):
            """
            :type s: str
            :rtype: int
            """
            s = s.replace(' ', '')
            # Store all number and operators in list.
            num = []
            numStr = []
            op = []
            i = 0
            while i < len(s):
                if s[i] >= '0' and s[i] <= '9':
                    numStr.append(s[i])
                elif s[i]=='+' or s[i]=='-' or s[i]=='*' or s[i]=='/':
                    num.append(int(''.join(numStr)))
                    del numStr[:]
                    op.append(s[i])
                i += 1    
            if len(numStr) != 0:
                num.append(int(''.join(numStr)))
            # Transform all a*b into 0+(a*b).
            for i in range(len(op)):
                if op[i] == '*':
                    num[i+1] = num[i] * num[i+1]
                elif op[i] == '/':
                    num[i+1] = num[i] / num[i+1]
                if op[i]=='*' or op[i]=='/':
                    num[i] = 0
                    if i != 0:
                        op[i] = op[i-1]
                    else:
                        op[i] = '+'                
            # Calculate + and - from left to right.
            res = num[0]
            for i in range(len(op)):
                if op[i] == '+':
                    res += num[i+1]
                elif op[i] == '-':
                    res -= num[i+1]
            return res
    

Log in to reply
 

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