29. Divide Two Integers
1 class Solution { 2 public int divide(int dividend, int divisor) { 3 long count = 0; 4 if(dividend == 0) return 0; 5 //divisor和dividend都要变成正数和long再进行处理 6 if((dividend > 0 && divisor >0) || (dividend < 0 && divisor < 0)) { 7 long ldivisor = Math.abs((long)divisor); 8 long ldividend = Math.abs((long)dividend); 9 count = longdivide(ldividend, ldivisor); 10 11 }else { 12 long ldivisor = Math.abs((long)divisor); 13 long ldividend = Math.abs((long)dividend); 14 count = -longdivide(ldividend, ldivisor); 15 } 16 17 //overflow处理 18 if(count > 0) { 19 return (int) (count > Integer.MAX_VALUE ? Integer.MAX_VALUE : count); 20 }else { 21 return (int) (count < Integer.MIN_VALUE ? Integer.MIN_VALUE : count); 22 } 23 24 25 } 26 27 //类似binary search 28 public long longdivide(long dividend, long divisor) { 29 if(dividend < divisor) return 0; 30 long multiple = 1; 31 long sum = divisor; 32 while((sum + sum) < dividend) { 33 sum += sum; 34 multiple +=multiple; 35 } 36 return multiple + longdivide(dividend - sum, divisor); 37 38 } 39 }