leetcode -- Divide Two Integers

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

1.naive的做法是用除数一个一个减被除数,直到被除数<=0, 此方法会超时!!!

2.将被除数向左移位(x2),然后与被除数做比较,直到发现仅次于被除数的那个值,减去该值后继续(line:24-30)。

 1 public class Solution {
 2     public static int divide(int dividend, int divisor) {
 3         if (dividend == 0 || divisor == 1)
 4             return dividend;
 5             
 6         int sign = 1;
 7         if (dividend < 0)
 8             sign = sign * -1;
 9         if (divisor < 0)
10             sign = sign * -1;
11 
12         long divid = Math.abs((long)dividend);
13         long divis = Math.abs((long)divisor);
14 
15         long[] a = new long[32];
16         int i = 0;
17         while (divis > 0 && divis <= divid) {
18             a[i] = divis;
19             divis = divis << 1;
20             i++;
21         }
22         i--;
23         long res = 0;
24         while ( divid > 0 && i >= 0) {
25             if(divid >= a[i]){
26                 divid = divid - a[i];
27                 res = res + (1 << i);
28             }
29             i--;
30         }
31         return (int)(res * sign) ;
32     }
33 }

使用int时会出现整数溢出问题,INT_MIN(-2147483648),比如 abs(-2147483648) = -2147483648,这里在12、13行全部使用long

另外+的优先级要比<<高

 

ref:http://fisherlei.blogspot.com/2012/12/leetcode-divide-two-integers.html

你可能感兴趣的:(LeetCode)