Java [leetcode 29]Divide Two Integers
2015-05-16 11:49
423 查看
题目描述:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
解题思路:
把除数表示为:dividend = 2^i * divisor + 2^(i-1) * divisor + ... + 2^0 * divisor。这样一来,我们所求的商就是各系数之和了,而每个系数都可以通过移位操作获得。
详细解说请参考:http://blog.csdn.net/whuwangyi/article/details/40995863
代码如下:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
解题思路:
把除数表示为:dividend = 2^i * divisor + 2^(i-1) * divisor + ... + 2^0 * divisor。这样一来,我们所求的商就是各系数之和了,而每个系数都可以通过移位操作获得。
详细解说请参考:http://blog.csdn.net/whuwangyi/article/details/40995863
代码如下:
public class Solution { public int divide(int dividend, int divisor) { boolean flag = (dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0); long absDividend = Math.abs((long) dividend); long absDivisor = Math.abs((long) divisor); long quotient = dividePositive(absDividend, absDivisor); if (flag && quotient > Integer.MAX_VALUE) return Integer.MAX_VALUE; return flag ? (int) quotient : -(int) quotient; } public long dividePositive(long dividend, long divisor) { if (dividend < divisor) return 0; long quotient = 1; long originalDivisor = divisor; while (dividend >= (divisor << 1)) { quotient <<= 1; divisor <<= 1; } return quotient + dividePositive(dividend - divisor, originalDivisor); } }
相关文章推荐
- LeetCode 29 Divide Two Integers (C,C++,Java,Python)
- (Java)LeetCode-29. Divide Two Integers
- [LeetCode-Java]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]problem 29. Divide Two Integers
- LeetCode-29-Divide Two Integers(Numbers)-Medium
- 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(C)
- LeetCode-29-Divide Two Integers 智障题
- leetCode 29.Divide Two Integers (两整数相除) 解题思路和方法
- Leetcode 29. Divide Two Integers
- [Leetcode] Divide Two Integers (Java)
- leetcode题解-29. Divide Two Integers