Leetcode 29. Divide Two Integers (Medium) (cpp)
2016-08-17 18:06
363 查看
Leetcode 29. Divide Two Integers (Medium) (cpp)
Tag: Math, Binary Search
Difficulty: Medium
/*
29. Divide Two Integers (Medium)
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 (!dividend) {
return 0;
}
if (!divisor || dividend == INT_MIN && divisor == -1) {
return INT_MAX;
}
int sign = (dividend > 0 ^ divisor > 0) ? -1 : 1;
long dd = labs((long)dividend), dr = labs((long)divisor);
if (dd < dr) {
return 0;
}
int h = 0;
long t = dr;
while (t <= dd) {
t <<= 1;
h++;
}
long ret = 1 << --h;
dd -= (t >>= 1);
while (dd >= dr) {
while (t > dd){
t >>= 1;
h--;
}
ret |= 1 << h;
dd -= t;
}
return sign < 0 ? -ret : ret;
}
};
Tag: Math, Binary Search
Difficulty: Medium
/*
29. Divide Two Integers (Medium)
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 (!dividend) {
return 0;
}
if (!divisor || dividend == INT_MIN && divisor == -1) {
return INT_MAX;
}
int sign = (dividend > 0 ^ divisor > 0) ? -1 : 1;
long dd = labs((long)dividend), dr = labs((long)divisor);
if (dd < dr) {
return 0;
}
int h = 0;
long t = dr;
while (t <= dd) {
t <<= 1;
h++;
}
long ret = 1 << --h;
dd -= (t >>= 1);
while (dd >= dr) {
while (t > dd){
t >>= 1;
h--;
}
ret |= 1 << h;
dd -= t;
}
return sign < 0 ? -ret : ret;
}
};
相关文章推荐
- LeetCode:29.Divide Two Integers[Medium]
- LeetCode-29-Divide Two Integers(Numbers)-Medium
- [Leetcode 29, medium] Divide two integers
- LeetCode 29. Divide Two Integers
- LeetCode 29:Divide Two Integers
- leetcode 29. Divide Two Integers
- [leetcode]29. Divide Two Integers
- leetcode-29-Divide Two Integers
- leetcode 29. Divide Two Integers
- LeetCode_OJ【29】Divide Two Integers
- 【Leetcode】【Medium】Divide Two Integers
- LeetCode 29. Divide Two Integers
- leetcode 29. Divide Two Integers
- LeetCode 29 Divide Two Integers
- leetcode 29. Divide Two Integers
- leetcode 29. Divide Two Integers
- Leetcode29 Divide Two Integers
- LeetCode (29)Divide Two Integers
- Leetcode 29. Divide Two Integers
- LeetCode 29 Divide Two Integers (C,C++,Java,Python)