LeetCode Divide Two Integers

题目:

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

class Solution {
public:
	int divide(int dividend, int divisor) {
		int flag = 1;
		//判断符号
		if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0))
			flag = -1;
		int ans;
		long long m = abs((long long)dividend);
		long long n = abs((long long)divisor);
		long long beg = 0, end = m;
		long long mid;
		long long tmp;
		while (beg <= end) {
			mid = (beg + end) >> 1;
			tmp = mul(mid, n);
			if (tmp == m) {
				ans = mid;
				break;
			}
			else if (tmp > m)
				end = mid - 1;
			else {
				ans = mid;
				beg = mid + 1;
			}
		}
		return flag < 0 ? -ans : ans;
	}
	//实现mid*divisor
	long long mul(long long mid, long long divisor) {
		if (mid == 0)
			return 0;
		long long tmp = mul(mid >> 1, divisor) << 1;
		//若为奇数,结果加上一个divisor
		if (mid & 1)
			tmp += divisor;
		return tmp;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值