[LintCode] Divide Two Integers 两数相除
2016-08-08 23:52
459 查看
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return
Have you met this question in a real interview?
Example
Given dividend =
LeetCode上的原题,请参见我之前的博客Divide Two Integers。
解法一:
解法二:
解法三:
If it is overflow, return
2147483647
Have you met this question in a real interview?
Example
Given dividend =
100and divisor =
9, return
11.
LeetCode上的原题,请参见我之前的博客Divide Two Integers。
解法一:
class Solution { public: /** * @param dividend the dividend * @param divisor the divisor * @return the result */ int divide(int dividend, int divisor) { if (divisor == 0 || (dividend == INT_MIN && divisor == -1)) return INT_MAX; long long m = abs((long long)dividend), n = abs((long long)divisor), res = 0; int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; if (n == 1) return sign == 1 ? m : -m; while (m >= n) { long long t = n, p = 1; while (m >= (t << 1)) { t <<= 1; p <<= 1; } res += p; m -= t; } return sign == 1 ? res : -res; } };
解法二:
class Solution { public: /** * @param dividend the dividend * @param divisor the divisor * @return the result */ int divide(int dividend, int divisor) { long long m = abs((long long)dividend), n = abs((long long)divisor), res = 0; if (m < n) return 0; while (m >= n) { long long t = n, p = 1; while (m > (t << 1)) { t <<= 1; p <<= 1; } res += p; m -= t; } if ((dividend < 0) ^ (divisor < 0)) res = -res; return res > INT_MAX ? INT_MAX : res; } };
解法三:
class Solution { public: /** * @param dividend the dividend * @param divisor the divisor * @return the result */ int divide(int dividend, int divisor) { long long m = abs((long long)dividend), n = abs((long long)divisor), res = 0; if (m < n) return 0; long long t = n, p = 1; while (m > (t << 1)) { t <<= 1; p <<= 1; } res += p + divide(m - t, n); if ((dividend < 0) ^ (divisor < 0)) res = -res; return res > INT_MAX ? INT_MAX : res; } };
相关文章推荐
- [Leetcode] divide two integers 两数相除
- [LeetCode] 29. Divide Two Integers 两数相除
- LeetCode Divide Two Integers 不使用除号取模乘号实现两数相除
- [LeetCode] Divide Two Integers 两数相除
- LeetCode OJ:Divide Two Integers(两数相除)
- LeetCode之操作两个数相除DivideTwoIntegers
- 5.divide-two-integers(两个整数相除)
- Divide Two Integers 两个整数相除
- LeetCode | Divide Two Integers(两个数相除)
- Leetcode刷题记——29. Divide Two Integers(整数相除Divide two integers without using multiplication, division)
- leetCode 29.Divide Two Integers (两整数相除) 解题思路和方法
- leetcode 29 Divide Two Integers(整数相除)
- [LeetCode-29] Divide Two Integers(两个整数相除,不能使用乘除取余算术符)
- Leet Code 29 Divide Two Integers - 两个整数相除 - Java
- **[Lintcode]Divide Two Integers
- Divide two numbers,两数相除求商,不能用乘法,除法,取模运算
- LeetCode 29 Divide Two Integers(两个整数相除)(*)
- LeetCode OJ 之 Divide Two Integers (两个整数相除)
- lintcode-medium-Divide Two Integers
- 【LeetCode-面试算法经典-Java实现】【029-Divide Two Integers(两个整数相除)】