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

## 翻译

不用乘法、除法、取余操作，将两个数相除。

## 原文

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

If it is overflow, return MAX_INT.

## 代码

class Solution {
public:
int divide(int dividend, int divisor) {
if(!divisor) return INT_MAX;
if(divisor == 1) return dividend;
if(divisor == -1) {
if(dividend == INT_MIN) return INT_MAX;
else return -dividend;
}

bool s1 = dividend < 0;
bool s2 = divisor < 0;

unsigned int nom = s1 ? -dividend : dividend;
unsigned int den = s2 ? -divisor : divisor;

unsigned int rem = 0;
unsigned int quot = 0;

for(int i = 31; i >= 0; --i) {
rem <<= 1;
rem |= (nom >> i) & 1;
if(rem >= den) {
rem -= den;
quot |= (1 << i);
}
}

return s1^s2? -quot : quot;
}
};

public class Solution
{
public int Divide(int dividend, int divisor)
{
//1. check overflow: 2 ways of over flow 1) 0 divisor; 2) int.Minvalue/(-1)
if (divisor == 0 || dividend == int.MinValue && divisor == -1) return int.MaxValue;
//2. calculate sign
int sign = dividend > 0 ^ divisor > 0 ? -1 : 1, result = 0;
long m = Math.Abs((long)dividend), n = Math.Abs((long)divisor);
//3. looping from 1 to possible maximum pow(2, x) to add into result
while (m >= n)
{
long subN = n;
for (int subCount = 1; m >= subN; subCount <<= 1, subN <<= 1)
{
m -= subN;
result += subCount;
}
}
return result * sign;
}
}
public class Solution
{
public int Divide(int dividend, int divisor)
{
if (divisor == 1) return dividend;
if (dividend == int.MinValue && divisor == -1 || divisor == 0) return int.MaxValue;
int sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1, result = 0;
long dvd = Math.Abs((long)dividend), dvs = Math.Abs((long)divisor);
while (dvd >= dvs)
{
long sub = dvs;
int subR = 1;
while (dvd >= (sub << 1))
{ sub <<= 1; subR <<= 1; }
dvd -= sub;
result += subR;
}
return sign * result;
}
}

nomasp

• 擅长领域：
• android

#### 【LeetCode-面试算法经典-Java实现】【029-Divide Two Integers（两个整数相除）】

2015-07-25 08:12:27

#### leetCode 29.Divide Two Integers (两整数相除) 解题思路和方法

2015-07-07 23:26:53

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

2015-09-15 19:01:09

#### LeetCode之操作两个数相除DivideTwoIntegers

2016-07-25 16:48:19

#### leetcode 29 -- Divide Two Integers

2015-06-12 17:23:05

#### LeetCode OJ 之 Divide Two Integers (两个整数相除）

2014-11-21 21:36:45

#### leetcode29. 两数相除

2018-04-12 20:58:01

#### Leetcode #29 Divide Two Integers 整数相除 解题报告

2016-03-31 23:39:52

#### leetcode 29. 两数相除

2018-05-14 21:36:53

#### python写算法题：leetcode: 29. Divide Two Integers

2017-07-04 19:43:44