您的位置:首页 > 编程语言 > Java开发

LeetCode_29---Divide Two Integers

2015-06-12 15:32 537 查看
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.

Hide Tags
 Math Binary
Search

Code:

package From21;

/**
* @author MohnSnow
* @time 2015年6月12日 下午2:57:51
* @title 模拟除法
*/
public class LeetCode29 {

/**
* @param argsmengdx
* -fnst
*/
//https://leetcode.com/discuss/27558/my-ac-java-solution-33-line-227ms-without-long-long
public static int divide(int dividend, int divisor) {
//特殊情况
if (divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1))
return Integer.MAX_VALUE;//溢出
if (dividend != Integer.MIN_VALUE && Math.abs(dividend) < Math.abs(divisor))
return 0;
if (divisor == Integer.MIN_VALUE)
return (dividend == Integer.MIN_VALUE) ? 1 : 0;
boolean flag = (dividend < 0) ^ (divisor < 0);//被除数与除数是否异号
dividend = -Math.abs(dividend);
divisor = -Math.abs(divisor);
int[] num = new int[40];
int[] multiple = new int[40];
num[1] = divisor;
multiple[1] = 1;
for (int i = 2; i < 32 && num[i - 1] < 0; ++i) {
num[i] = num[i - 1] << 1;
multiple[i] = multiple[i - 1] << 1;
}
int result = 0;
int index = 1;
while (num[index] < 0)
++index;
index -= 1;
while (dividend <= divisor) {
while (dividend <= num[index]) {
result += multiple[index];
dividend -= num[index];
}
--index;
}
return !flag ? result : -result;
}

//https://leetcode.com/discuss/23966/accepted-java-solution-with-comments
//272ms
public static int divide1(int dividend, int divisor) {
long result = divideLong(dividend, divisor);
return result > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) result;
}

// It's easy to handle edge cases when
// operate with long numbers rather than int
public static long divideLong(long dividend, long divisor) {
// Remember the sign--判断最后符号的一行代码
boolean negative = dividend < 0 != divisor < 0;
// Make dividend and divisor unsign
if (dividend < 0)
dividend = -dividend;
if (divisor < 0)
divisor = -divisor;
// Return if nothing to divide被除数小于除数
if (dividend < divisor)
return 0;
// Sum divisor 2, 4, 8, 16, 32 .... times--缩短处理次数
long sum = divisor;
long divide = 1;
while ((sum + sum) <= dividend) {
sum += sum;
divide += divide;
}
// Make a recursive call for (devided-sum) and add it to the result
return negative ? -(divide + divideLong((dividend - sum), divisor)) :
(divide + divideLong((dividend - sum), divisor));
}

public static void main(String[] args) {
int a = 8;
int b = 3;
System.out.println("除数:" + divide(a, b));
System.out.println("除数:" + divide1(a, b));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode java 算法