剑指 Offer II 001. 整数除法

image.png

原题链接:https://leetcode-cn.com/problems/xoh6Oh/

解题思路:

Python代码

class Solution:
    def divide(self, a: int, b: int) -> int:
        Int_MAX = 2**31 - 1
        if b == 0:
            return Int_MAX

        neg = a > 0 and b < 0 or a < 0 and b > 0
        a, b = abs(a), abs(b)
        ans, shift = 0, 31
        while shift >= 0:
            if a >= b << shift:
                a -= b<<shift
                ans += 1<<shift
            shift -= 1

        if neg:
            ans = -ans

        if ans > Int_MAX:
            return Int_MAX

        return ans
        
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容