29. Divide Two Integers

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

If it is overflow, return 2147483647

Example

Given dividend = 100 and divisor = 9, return 11.

分析:

这本身并不难,难的是里面有很多想不到的test case。比如:

a = -2147483648 && b = -1, 应该返回 2147483647

a = -2147483648 && b = 2  应该返回 -1073741824

这题的终极解法应该是用bit operators.  原理是快速找出最大的以divisor为底数的值,当然这值必须要小于dividend。假设那个值是K, 那么我们可以确定。 dividend / divisor =  K / divisor + (dividend - K) / divisor.

如何快速找出最大的以divisor为底数的值呢,用 << Operator.

 1 public class Solution {
 2     public int divide(int dividend, int divisor) {
 3         if (dividend == 0) return 0;
 4         if (divisor == 1) return dividend;
 5         if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
 6  
 7         boolean isNegative = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0);
 8         // case: -2147483648, 2
 9         long a = Math.abs((long) dividend), b = Math.abs((long) divisor);
10  
11         int result = 0;
12         // if we divide 100 by 5 by using for loop, we need to iterate for 20 times (answer). Can we make it shorter? 
13         // The answer is we can increase the answer by 2 times each time until divisor * answer > dividend.
14         while (a >= b) {
15             int shift = 0;
16             for (; a >= (b << shift); shift++);
17             a -= b << (shift - 1); // 剩余部分
18             result += 1 << (shift - 1); 
19         }
20         return isNegative ? -result : result;
21     }
22 }

 

Reference:

http://www.jiuzhang.com/solutions/divide-two-integers/

 

posted @ 2016-07-13 22:39  北叶青藤  阅读(158)  评论(0编辑  收藏  举报