LeetCode_29---Divide Two Integers

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));
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值