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


發佈了202 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章