[Leetcode]Divide Two Integers

来源:互联网 发布:什么叫多线程编程 编辑:程序博客网 时间:2024/06/11 00:33

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

If it is overflow, return MAX_INT.


class Solution {public:    /*algorithm binary search     */    int bSearch(long d1,long d2){        long l = 1,h = d1;        while(l <= h){            long m = (l+h)>>1;            long d = d1 - m*d2;            if(0 <= d && d < d2){                return m;            }else if(d >= d2){                l = m+1;            }else{                h = m-1;            }        }    }    int divide(int dividend, int divisor) {        long d1 = labs(dividend),d2 = labs(divisor);//use labs,instead of abs,or -        bool neg = (dividend^divisor)>>sizeof(int)*8-1;//d1<0&&d2 >0 || d1>0||d2<0        if(d1 == 0 || d1 < d2)return 0;        if(d2 == 1 && d1 > INT_MAX)return neg?-d1:INT_MAX;        long count=bSearch(d1,d2);        return neg?-count:count;    }};


0 0
原创粉丝点击