美文网首页
29. Divide Two Integers

29. Divide Two Integers

作者: 夜皇雪 | 来源:发表于2016-11-24 06:33 被阅读0次
public class Solution {
    public int divide(int dividend, int divisor) {
        int sign=1;
        if((dividend>0&&divisor<0)||(dividend<0&&divisor>0)) sign=-1;
        long ldividend=Math.abs((long)dividend);
        long ldivisor=Math.abs((long)divisor);
        if(dividend==0||(ldividend<ldivisor)) return 0;
        long lans=ldivide(ldividend,ldivisor);
        int ans;
        if(lans>Integer.MAX_VALUE){
            ans = (sign == 1)? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }else ans=(int)(sign*lans);
        return ans;
    }
    private long ldivide(long ldividend,long ldivisor){
        if(ldividend<ldivisor) return 0;
        long sum=ldivisor;
        long multiple=1;
        while((sum+sum)<=ldividend){
            sum+=sum;
            multiple+=multiple;
        }
        return multiple+ldivide(ldividend-sum,ldivisor);
    }
}

相关文章

网友评论

      本文标题:29. Divide Two Integers

      本文链接:https://www.haomeiwen.com/subject/aphbpttx.html