In the pydev on my machine, I can get the correct answer for "999"*"999", but wrong answer when submitted


  • 0
    V

    So wired that the oj gives the answer for "999","999" is "8991"

    class Solution:
        # @param num1, a string
        # @param num2, a string
        # @return a string
        cache = {}
        def multiply(self, num1, num2):
            
            if num1=="0" or num2=="0":
                return "0"
            
            if (len(num1)>len(num2)):
                num1,num2 = num2, num1
            
            res = []
            cnt = 0
            for i in range(len(num2)-1, -1, -1):
                if int(num2[i])==0:
                    cnt +=1
                    continue            
                
                mm = self.multiplyStringBySingleNum(num1, int(num2[i]))
                if cnt>0:
                    mm = mm + "0"*cnt
                cnt +=1
                res = [mm] + res
            return  self.sumStrings(res)
        
        def sumStrings(self, ss):
            #print ss
            length = len(ss[0])
            lengthSS = len(ss)
            paddedss = [x.zfill(length) for x in ss]
            #print paddedss
            res = []
            carry = 0
            for i in range(length-1,-1,-1):
                sum = 0
                for j in range(lengthSS):
                    sum +=int(paddedss[j][i])
                sum += carry
                res = [str(sum%10)] + res
                carry = sum/10
            if carry!=0:    
                res = [str(carry)] + res
            return "".join(res)
                
        
        def multiplyStringBySingleNum(self,num, singleDigit):
            
            if self.cache.has_key(singleDigit):
                #print "hit buffer"
                return self.cache[singleDigit]
            
            res = []
            carry = 0
            for i in range(len(num)-1,-1,-1):
                pp = int(num[i]) * singleDigit + carry
                res = [str(pp%10)] + res
                carry = pp/10
            if carry!=0:    
                res = [str(carry)] + res
            retVal = "".join(res)
            self.cache[singleDigit]=retVal
            
            return retVal
    
        
    sol = Solution()
    print sol.multiply("999", "999")

Log in to reply
 

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