【leetcode】29. Divide Two Integers

题目如下:

解题思路:除法就是减法。但是遇到比较BT的用例 pow(2,31)/1,需要对方法进行改进。改进的方案是依次增大除数,每次对除数扩大两倍。

代码如下:

class Solution:
    # @param {integer} dividend
    # @param {integer} divisor
    # @return {integer}
    def divide(self, dividend, divisor):
        if divisor == 0:
            return 0

        flag = ''
        if dividend < 0 and divisor < 0:
            dividend = -dividend
            divisor = -divisor
        elif dividend < 0 and divisor > 0:
            flag = '-'
            dividend = -dividend
        elif dividend > 0 and divisor < 0:
            flag = '-'
            divisor = -divisor

        count = 0
        while dividend >= divisor:
            new_divisor = divisor
            times = 0
            while dividend >= new_divisor:
                dividend -= new_divisor
                if times == 0:
                    times = 1
                else:
                    times += times
                count += times
                new_divisor += new_divisor

        if flag == '-':
            if count > 2147483648:
                count = 2147483648
            count = -count
        else:
            if count > 2147483647:
                count = 2147483647
        return count

 

posted @ 2018-08-27 13:44  seyjs  阅读(143)  评论(0编辑  收藏  举报