# 29. Divide Two Integers

Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.

f(24,5)=24/5=20/5+4/5=4+0=4
5左移2位就是20，而左移3位就是40超过了24，因此第一部分商为22=4.

#include<iostream>
#include<math.h>
using namespace std;
class Solution {
public:
int divide(int dividend, int divisor)
{
if(0==divisor||(INT_MIN==dividend&&divisor==-1))
return INT_MAX;//排除特殊情况
__int64 x=fabs(dividend);
__int64 y=fabs(divisor);
int result=0;
while(x>=y)
{
__int64 temp=y;
__int64 count=1;
while(temp<=x)
{
temp=temp<<1;
count=count<<1;
}
result=result+(count>>1);
x=x-(temp>>1);
}
if((dividend<0)^(divisor<0))
result=-result;
return result;
}
};
int main()
{
Solution solve;
int x,y,result;
cin>>x>>y;
result=solve.divide(x,y);
cout<<result<<endl;
return 0;
}

class Solution {
public:
int divide(int dividend, int divisor)
{
if(0==divisor||(INT_MIN==dividend&&divisor==-1))
return INT_MAX;
long long x=labs(dividend);
long long y=labs(divisor);
int result=0;
while(x>=y)
{
long long temp=y;
long long count=1;
while(temp<=x)
{
temp=temp<<1;
count=count<<1;
}
result=result+(count>>1);
x=x-(temp>>1);
}
if((dividend<0)^(divisor<0))
result=-result;
return result;
}
};

#### LeetCode --- 29. Divide Two Integers

2015-02-02 21:58:27

#### [Leetcode]29. Divide Two Integers @python

2016-01-16 16:48:08

#### LeetCode29DivideTwoIntegers--In Java

2016-02-22 20:24:54

#### LeetCode(29)Divide Two Integers

2014-01-03 07:24:18

#### LeetCode 29 Divide Two Integers (C,C++,Java,Python)

2015-05-13 09:27:20

#### leetcode 29 -- Divide Two Integers

2015-06-12 17:23:05

#### [LeetCode]29.Divide Two Integers

2015-01-25 10:41:25

#### LeetCode 29 Divide Two Integers 除法的原理

2015-08-22 22:19:59

#### LeetCode 29 Divide Two Integers（两个整数相除）（*）

2015-11-17 20:04:53

#### [LeetCode-29] Divide Two Integers（两个整数相除，不用乘除取余算术符）

2015-09-15 19:01:09