leetcode--29. 两数相除

题目:29. 两数相除

链接:https://leetcode-cn.com/problems/divide-two-integers/description/

计算两个数相除的结果,要求不用乘除和取模。其实就是模拟手算吧,我用减法写的。

python:

class Solution:
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        MAX_INT=0x7fffffff
        MIN_INT=-0x80000000
        def smallDiv(dividend, divisor):
            ret = 0
            while dividend - divisor >= 0:
                ret += 1
                dividend -= divisor
            return [ret, dividend]

        def mydivide(dividend, divisor):
            ret, mod = "", ""
            flag = (dividend < 0) ^ (divisor < 0)
            dividend = -dividend if dividend<0 else dividend
            divisor = - divisor if divisor<0 else divisor
            dividend = (list(map(int, list(str(dividend)))))
            for num in dividend:
                mod = (int)(mod + str(num))
                temp = smallDiv(mod, divisor)
                ret += str(temp[0])
                mod = str(temp[1])
            if flag:
                return -int(ret)
            return int(ret)
        ret=mydivide(dividend, divisor)
        if ret>MAX_INT:
            return MAX_INT
        if ret<MIN_INT:
            return MIN_INT
        return ret

发布了112 篇原创文章 · 获赞 104 · 访问量 11万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览