题目来源:https://leetcode.com/problems/divide-two-integers/
问题描述
29. Divide Two Integers
Medium
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividendby 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.
------------------------------------------------------------
题意
不用乘、除和求模运算实现有符号整数的整数除法,返回整除结果。
------------------------------------------------------------
思路
题目的tag是Binary Search, 其实我的做法不算真正的Binary Search,只能说是借鉴了Binary Search的思想。既然不能使用乘除,则用减法模拟除法。但是当被除数A是除数B的很多倍时,减法执行次数过多,会超时。该算法的时间复杂度是O(A/B)。
我的解决方案是仍用减法代替除法,但是每次减去2^n*B, 使得2^n*B < A且2^(n+1)*B > A. 这样的时间复杂度是O((log(A/B)^2).
------------------------------------------------------------
代码
class Solution {
public int divide(int dividend, int divisor) {
if (dividend == 0)
{
return 0;
}
boolean sign = true;
long l_dividend = (long)dividend, l_divisor = (long)divisor, ans = 0, res = 0, mydivisor = divisor, addi = 0;
if ((l_dividend < 0 && l_divisor > 0) || (l_dividend > 0 && l_divisor < 0))
{
sign = false;
}
if (l_dividend < 0)
{
l_dividend = -l_dividend;
}
if (l_divisor < 0)
{
l_divisor = -l_divisor;
}
while(true)
{
mydivisor = l_divisor;
res = l_dividend - mydivisor;
if (res < 0)
{
break;
}
addi = 1;
while (res > mydivisor)
{
mydivisor <<= 1;
addi <<= 1;
res = l_dividend - mydivisor;
}
ans += addi;
l_dividend = res;
}
ans = sign? ans:-ans;
if (ans > Integer.MAX_VALUE)
{
ans = Integer.MAX_VALUE;
}
if (ans < Integer.MIN_VALUE)
{
ans = Integer.MIN_VALUE;
}
return (int)ans;
}
}