首页 > 代码库 > Divide Two Integers

Divide Two Integers

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

代码:

class Solution {private:    int res;public:    int solve(long long dividend, long long divisor){        long long temp=1;        while (divisor<=dividend)        {            divisor=divisor<<1;            temp=temp<<1;        }        divisor=divisor>>1;        temp=temp>>1;        res+=temp;        return dividend-divisor;    }    int divide(int dividend, int divisor) {        res=0;        bool fu=false;        if(divisor==0) return -1;        if(divisor==1) return dividend;        long long my_dividend=(long long)dividend;        long long my_divisor=(long long)divisor;        if(my_dividend<0&&my_divisor<0){            my_dividend=0-my_dividend;            my_divisor=0-my_divisor;            fu=false;        }        if(my_dividend<0) {my_dividend=-my_dividend;fu=true;}        if(my_divisor<0) {my_divisor=-my_divisor;fu=true;}        while (((my_dividend=solve(my_dividend,my_divisor))-my_divisor)>=0);        if(fu) res=-res;        return res;    }};int main(){    freopen("C:\\Users\\Administrator\\Desktop\\a.txt","r",stdin);    Solution so;    int a=0-2147483648;    int b=0-1017100424;    cout<<so.divide(a,b)<<endl;    return 0;}

 

Divide Two Integers