首页 > 代码库 > Divide Two Integers

Divide Two Integers

参考:http://www.cnblogs.com/springfor/p/3871008.html

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

If it is overflow, return MAX_INT.

这道看了网上的很多都是通过移位来做的,硬是没看懂

看了一下这个锅锅的,终于懂了

 1 public class Solution { 2     public int divide(int dividend, int divisor) { 3         if(0 == dividend || 0 == divisor) 4             return 0; 5         boolean isNeg = ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) ? true : false; 6         long dividen_long = Math.abs((long)dividend); 7         long divisor_long = Math.abs((long)divisor); 8         if(divisor_long > dividen_long) 9             return 0;10         11         long sum = 0;12         long pow = 0;13         long result = 0;14         15         while(divisor_long <= dividen_long){16             sum = divisor_long;17             pow = 1;18             while(sum + sum <= dividen_long){19                 sum += sum;20                 pow += pow;21             }//while22             dividen_long -= sum;23             result += pow;24         }//while25         26         result = isNeg ?  -result : result;27         if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)28             return Integer.MAX_VALUE;29         30         return (int)result;31     }32 }

 

Divide Two Integers