Divide Two Integers

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

 

Code:

 

class Solution {
public:
    int divide(int dividend, int divisor) {
        int quotient=0;
        long long d1=abs((long long)dividend); // change to type 64 bits, such as 'long long' or 'double'
        long long d2=abs((long long)divisor);  // change -2147483648 to positive
        while(d1>=d2){
            for(long long i=0,a=d2;d1>=a;i++,a<<=1){
                d1-=a;
                quotient+=1<<i;
            }
        }
        return ((dividend^divisor)>>31) ? (-quotient) : (quotient);
    }
};

 

posted @ 2013-11-05 07:45  WinsCoder  阅读(134)  评论(0编辑  收藏  举报