其他分享
首页 > 其他分享> > 29. 两数相除 - LeetCode

29. 两数相除 - LeetCode

作者:互联网

29. 两数相除

题目链接

二分+倍增

class Solution {
    public int divide(int dividend, int divisor) {
        if(dividend == 0)
            return 0;
        if(dividend == Integer.MIN_VALUE && divisor == -1)
            return Integer.MAX_VALUE;
        int signal = (dividend ^ divisor) < 0 ? -1 : 1;
        long a = Math.abs((long)dividend);
        long b = Math.abs((long)divisor);
        long l = 0, r = a;
        while(l < r){
            long mid = (l + r + 1) >> 1;
            long c = mul(mid, b);
            if(c < a) l = mid;
            else if(c > a) r = mid - 1;
            else return signal * (int) mid;
        }
        return signal * (int) l;
    }
    private long mul(long a, long b){
        long ans = 0;
        while(a > 0){
            if((a & 1) == 1)
                ans += b;
            a >>= 1;
            b <<= 1;
        }
        return ans;
    }
}

二进制枚举


class Solution {
    public int divide(int dividend, int divisor) {
        if(dividend == 0)
            return 0;
        if(dividend == Integer.MIN_VALUE && divisor == -1)
            return Integer.MAX_VALUE;
        int signal = (dividend ^ divisor) < 0 ? -1 : 1;
        int ans = 0;
        long a = Math.abs((long)dividend);
        long b = Math.abs((long)divisor);
        for(int i = 32; i >=0; i--)
            if((a >> i) >= b){
                ans += (1 << i);
                a -= (b << i);
            }
        return signal * ans;
    }
}

标签:return,divisor,int,29,long,mid,相除,dividend,LeetCode
来源: https://www.cnblogs.com/xiafrog/p/14398568.html