7
7
class DivideTwoIntegers {
8
8
9
9
public static void main (String [] args ) {
10
-
10
+ DivideTwoIntegers d = new DivideTwoIntegers ();
11
+ System .out .println (d .divide (100 , 3 ));
11
12
}
12
13
13
14
/**
14
15
* Take care of special cases, 0, +1, -1
15
16
* dividend = a0 * 1 * divisor + a1 * 2 * divisor + a2 * 2^2 * divisor...
16
- *
17
+ * ai can be 0 or 1, set it to 1 if dividend >= ai * 2^i * divisor
18
+ * All ais added up to result
17
19
*/
18
20
public int divide (int dividend , int divisor ) {
19
21
if (divisor == 0 ) return Integer .MAX_VALUE ;
20
22
if (dividend == 0 ) return 0 ;
21
23
if (divisor == 1 ) return dividend ;
22
24
if (divisor == -1 ) return dividend == Integer .MIN_VALUE ? Integer .MAX_VALUE : -dividend ;
23
25
final boolean neg = (dividend > 0 && divisor < 0 ) || (dividend < 0 && divisor > 0 );
24
- long ldividend = Math .abs ((long )dividend );
26
+ long ldividend = Math .abs ((long )dividend ); // convert to abstract long
25
27
final long ldivisor = Math .abs ((long )divisor );
26
28
int res = 0 ;
27
- for (int bit = Integer .SIZE - 1 ; bit >= 0 && ldividend >= ldivisor ; bit --) { // note how to initialize bit
29
+ for (int bit = Integer .SIZE - 1 ; bit >= 0 && ldividend >= ldivisor ; bit --) { // bit from 31 to 0, dividend >= divisor
28
30
if (ldividend >= (ldivisor << bit )) {
29
31
res |= 1 << bit ; // set 1 in relative bit in result
30
32
ldividend -= ldivisor << bit ;
31
33
}
32
34
}
33
35
return neg ? -res : res ;
34
36
}
35
- }
37
+ }
0 commit comments