Skip to content

Commit 7afd943

Browse files
committed
Updated divide two integers
1 parent 699579f commit 7afd943

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

Medium/DivideTwoIntegers.java

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,29 +7,31 @@
77
class DivideTwoIntegers {
88

99
public static void main(String[] args) {
10-
10+
DivideTwoIntegers d = new DivideTwoIntegers();
11+
System.out.println(d.divide(100, 3));
1112
}
1213

1314
/**
1415
* Take care of special cases, 0, +1, -1
1516
* 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
1719
*/
1820
public int divide(int dividend, int divisor) {
1921
if (divisor == 0) return Integer.MAX_VALUE;
2022
if (dividend == 0) return 0;
2123
if (divisor == 1) return dividend;
2224
if (divisor == -1) return dividend == Integer.MIN_VALUE ? Integer.MAX_VALUE : -dividend;
2325
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
2527
final long ldivisor = Math.abs((long)divisor);
2628
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
2830
if (ldividend >= (ldivisor << bit)) {
2931
res |= 1 << bit; // set 1 in relative bit in result
3032
ldividend -= ldivisor << bit;
3133
}
3234
}
3335
return neg ? -res : res;
3436
}
35-
}
37+
}

0 commit comments

Comments
 (0)