leetcode-29. Divide Two Integers

leetcode-29. Divide Two Integers

题目:

Divide two integers without using multiplication, division and mod operator.

第二遍做的时候还是没想起来。。其实就是二分法。但是跟一般的二分有点不一样。里面要嵌套一个while保证除数以2的幂的速度增长。这样先找结果的最高位,在找次高位以此类推。直到被除数小于除数。。总是是需要继续训练的题目。是经典的解法。。我这里从讨论里找了一个比较短的实现。

答案来源

public class Solution {
    public int divide(int a, int b) {
        if(a==Integer.MIN_VALUE){
            if(b==-1) return Integer.MAX_VALUE;
        }

        long x = a < 0 ? -(long)a : (long)a;
        long y = b < 0 ? -(long)b : (long)b;

        int res = recurse(x, y, 1);
        if(a < 0 && b < 0) return res;
        if(a < 0 || b < 0) return -res;
        return res;
    }

    public int recurse(long x, long y, int count) {
        if(x <= 0 || count==0) return 0;
        if(y > x) return recurse(x, y >>> 1, count >>> 1); //overshot, so divide and try again.
        else return recurse(x-y, y+y, count+count)+count;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值