1+ package leetcode .editor .en ;
2+ 3+ class DivideTwoIntegers {
4+ 5+ //leetcode submit region begin(Prohibit modification and deletion)
6+ class Solution {
7+ public int divide (int dividend , int divisor ) {
8+ int out = 0 ;
9+ boolean isNegative = dividend < 0 ^ divisor < 0 ;
10+ int remainingAbsDividend , absDivisor = abs (divisor );
11+ // special cases for INT_MIN:
12+ if (dividend == Integer .MIN_VALUE && divisor == Integer .MIN_VALUE ) return 1 ;
13+ if (divisor == Integer .MIN_VALUE ) return 0 ; // nothing has absolute value greater than INT_MIN, so its 0
14+ if (dividend == Integer .MIN_VALUE ){
15+ // only possibility for a result outside of integer range.
16+ if (divisor == -1 ) return Integer .MAX_VALUE ;
17+ int shift = 1 + largestLesserEqLeftShift (1 << 30 , absDivisor );
18+ out = 1 << shift ;
19+ int subtract = absDivisor << shift ;
20+ remainingAbsDividend = dividend - subtract ; // always positive
21+ } else {
22+ remainingAbsDividend = abs (dividend );
23+ }
24+ // normal cases
25+ if (remainingAbsDividend < absDivisor ) return isNegative ? neg (out ) : out ;
26+ while (remainingAbsDividend >= absDivisor ){
27+ int lShift = largestLesserEqLeftShift (remainingAbsDividend , absDivisor );
28+ remainingAbsDividend -= absDivisor << lShift ;
29+ out |= 1 << lShift ;
30+ }
31+ return isNegative ? neg (out ) : out ;
32+ }
33+ 34+ /**
35+ * Returns by how many bits can toShift be shifted left to still be lesser or equal to limit.
36+ * E.g. for limit=10010, toShift=101, result is 1 because 101<<1=1010, which is smaller than 10010.
37+ * @param limit positive integer
38+ * @param toShift positive integer
39+ * @return
40+ */
41+ int largestLesserEqLeftShift (int limit , int toShift ){
42+ int i = 0 ;
43+ while (limit >= toShift && toShift > 0 ) {
44+ toShift <<= 1 ;
45+ i ++;
46+ }
47+ return i - 1 ;
48+ }
49+ int abs (int x ){
50+ return x >= 0 ? x : neg (x );
51+ }
52+ int neg (int x ) {
53+ return ~x + 1 ;
54+ }
55+ 56+ }
57+ //leetcode submit region end(Prohibit modification and deletion)
58+ 59+ }
0 commit comments