首页 > 其他 > 详细

【LeetCode】Divide Two Integers

时间:2017-03-21 22:02:35      阅读:162      评论:0      收藏:0      [点我收藏+]

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

If it is overflow, return MAX_INT.

 

题目要求不能使用除号、乘号和取余操作符。

我们使用移位操作符。<< 左移代表乘以2,>>右移代表除以2

//a,b分别为被除数和除数
    public int divide(int a,int b){
        long res=0;
        int sign = 1;
        if((a<0 && b>0)||(a>0&&b<0)){
            sign = -1;
        }
        if(b==0||(a==Integer.MIN_VALUE&&b==-1)){
            return Integer.MAX_VALUE;
        }
        if(a<b){
            return 0;
        }
        while(a>b){
            long temp = b;
            long p = 1;
            while(a>=(temp<<1)){
                temp<<=1;
                p<<=1;
            }
            a-=temp;
            res+=p;
        }
        res = sign*res;
        return (int) res;
    }

 

【LeetCode】Divide Two Integers

原文:http://www.cnblogs.com/sMKing/p/6596734.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!