leetcode 29-> Divide Two Integers without using multiplication, division and mod operator

时间:2022-07-30 16:57:55

 

class Solution(object):
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        ispositive = True
        if dividend > 0 and divisor < 0:
            ispositive = False
        if dividend < 0 and divisor > 0:
            ispositive = False
        dividend = abs(dividend);divisor = abs(divisor)
        if dividend < divisor:
            return 0
        num = [1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000]
        i = 9
        newdividend = []
        while i >= 0:
            tmp = 0
            while dividend >= num[i]:
                tmp += 1;dividend -= num[i]
            newdividend.append(tmp); i -= 1
        tmpm = 0; ans = 0 ;i = 0
        while i < 10:
            while tmpm < divisor:
                if i > 9:
                    break
                j = 0; t = 0
                while j < 10 and tmpm != 0:
                    t += tmpm; j += 1
                tmpm = t + newdividend[i]; i += 1
                if tmpm < divisor:
                    j = 0; t = 0
                    while j < 10 and ans != 0:
                        t += ans; j += 1
                    ans = t
            if tmpm >= divisor:
                k = 0
                while tmpm >= divisor:
                    tmpm -= divisor; k += 1
                j = 0; t = 0
                while j < 10 and ans != 0:
                    t += ans; j += 1
                ans = t + k
        if ispositive:
            if ans > 2147483647:
                return 2147483647
            return ans
        if ans >= 2147483648:
            return -2147483648
        return 0 - ans