【LeetCode】29. Divide Two Integers

本文介绍了一种不使用乘法、除法和取模运算符的二进制除法算法,通过模拟二进制除法过程,实现整数除法。算法采用快速幂形式的叠乘方法,适用于大部分情况,但在绝对值相近时可能超时。通过参考高级算法,使用无符号64位整数避免溢出,确保在32位整数范围内正确返回商。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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: [−2^31,  2^31 − 1]. For the purpose of this problem, assume that your function returns 2^31 − 1 when the division result overflows.

 

描述:

给出被除数和除数,要求不使用乘法、除法和取模运算符,求出商,

其中除数不为0,如果商超过int的范围,则返回边界值

 

分析:

猜到是模拟二进制的除法,但是确实不知道怎么下手求,原先自己的思路是利用类似快速幂的形式进行叠乘,能解决一部分问题,但是对于两个数的绝对值比较接近的情况会超时,后来参看了大神的博客(链接点这里),发现自己还是太弱了,需要继续学习,其实也完全想过这种手动模拟的方法,可惜没有具体去实现,

 

另外,参考的博客代码也好像有点bug,因为对于某些数据64位整数也会溢出,建议使用无符号64位整数,不得不佩服后台数据的设计,边界把握的很好

 

来几组数据:

1026117192
-874002063
1004958205
-2137325331
-2147483648
-1
7
-3
10000
2
100
2
10
1
10
3
10
5
10
6
10
8
10
10
10
20

 

代码:(时间复杂度 O( log n)

class Solution {
public:
	int divide(int dividend, int divisor) {
		int sign = (dividend > 0) == (divisor > 0) ? 1 : -1;
		long long result = 0, a = abs(dividend), b = abs(divisor);
		while (a >= b) {
			unsigned long long temp = b, base = 1;
			while (temp << 1 < a) {
				temp <<= 1;
                base <<= 1;
			}
			a -= temp;
			result += base;
		}

		result = sign * result;
		if (result > INT_MAX || result < INT_MIN) {
			result = INT_MAX;
		}
		return (int)result; 
	}
	long long abs(long long x) {
		return x > 0 ? x : - x;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值