首页 > 代码库 > Divide Two Integers

Divide Two Integers

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

If it is overflow, return 2147483647

Have you met this question in a real interview? 
Yes
Example

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

 

思路: 1.用减法来实现除法(都预先转换成正数),用被除数 - 除数, 直到被除数 < 除数, 循环的次数即为商。 2. 为了加快速度,可以每次将除数 * 2,直到被除数 < 除数,同时记录加倍的次数 。 3. 注意corner case, int 的最小值还是其本身,因此需要用long来暂存。

 1 public class Solution {
 2     /**
 3      * @param dividend the dividend
 4      * @param divisor the divisor
 5      * @return the result
 6      */
 7     public int divide(int dividend, int divisor) {
 8         // Write your code here
 9         long a = dividend;
10         a = Math.abs(a);
11         long b = divisor;
12         b = Math.abs(b);
13         long result = 0;
14         while (a >= b) {
15             for (long tmp = b, count = 1; a >= tmp; tmp <<= 1, count <<= 1) {
16                 a -= tmp;
17                 result += count;
18             }
19         }
20         result = (((dividend ^ divisor) >> 31 & 1) == 1) ? -result : result;
21         if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
22             return Integer.MAX_VALUE;
23         }
24         return (int)result;
25     }
26 }

 

Divide Two Integers