[Leetcode]Divide Two Integers

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;
    }
};


阅读更多
文章标签: leetcode 算法
个人分类: Math Binary Search
上一篇[Leetcode]Reverse Words in a String
下一篇[Leetcode]Range Sum Query - Immutable
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭