Divide Two Integers

11 篇文章 0 订阅

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3

Example 2:

Input: dividend = 7, divisor = -3
Output: -2

Note:

  • Both dividend and divisor will be 32-bit signed integers.
  • The divisor will never be 0.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

大概意思,不要用* / 取模 这三个符号来计算除法
boolean isMinedNeg = false;
		boolean isMinsorNeg = false;
		boolean isNeg = false;
		if (dividend < 0) {
			isNeg = true;
			if (dividend == Integer.MIN_VALUE) {
				dividend = Integer.MAX_VALUE;
				isMinedNeg = true;
			} else {
				dividend = 0 - dividend;
			}
		}

		if (divisor < 0) {
			isNeg = !isNeg;
			if (divisor == Integer.MIN_VALUE) {
				divisor = Integer.MAX_VALUE;
				isMinsorNeg = true;
			} else {
				divisor = 0 - divisor;
			}
		}

		if(dividend < divisor || (isMinsorNeg && !isMinedNeg)) {
			return 0;
		}
		
		int oldtemp = 0;
		int oldcount = 0;
		int sum = 0;
		int mod = dividend - oldtemp;
		
		while(mod >= divisor) {
			int count = 1;
			int temp = divisor;
			while (mod >= temp) {
				if(temp < 0) {
					break;
				}
				oldtemp = temp;
				oldcount = count;
				temp += temp;
				count = count<<1;
			}
			mod = mod - oldtemp;
			sum += oldcount;
		}
		
		if(isNeg) {
			sum = 0 - sum;
			if(isMinedNeg && 1 + mod >= divisor) {
				sum -= 1;
			}
		}
		
		return sum;
我的大概思路,负数的全变成正数,不断的用1的两倍来解决效率的问题,举一个例子:60/3 
1.3+3=6 <= 60     1*2=2
   6+6=12 <= 60    2*2 =4
   12+12=24 <= 60  4*2=8
    24+24=48 <= 60  8*2=16
    48+48=96 > 60 中断
2.因为60 -48 =12
   3+3=6 <= 12     1*2=2
   6+6=12 <= 12   2*2=4
   12+12=24 > 12 中断
12-12=0

所以结果=16+4=20



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李文区

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值