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.
/**
* 通过递归的方式进行求解
* @param dividend
* @param divisor
* @return
*/
public static int Divide1(int dividend, int divisor)
{
if(dividend == 0) return 0;
if(divisor == 0) return Integer.MAX_VALUE;
int sign =1;
if((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0) )
{
sign = -1;
}
long ldividend = Math.abs((long)dividend);
long ldivisor = Math.abs((long)divisor);
long ans = ldivide(ldividend,ldivisor);
int result =0;
if(ans > Integer.MAX_VALUE)
result = (sign == 1)? Integer.MAX_VALUE:Integer.MIN_VALUE;
else
result = (int)(sign * ans);
return result;
}
public static long ldivide(long ldividend, long ldivisor)
{
if(ldividend < ldivisor) return 0;
long sum = ldivisor;
//当ldivisor < ldividend时,一定包含一个ldivisor,因此count为1
int count = 1;
while((sum + sum) < ldividend)
{
sum+=sum;
count += count;
}
return count + ldivide(ldividend - sum,ldivisor);
}
/**
* 利用迭代的方式求解
* @param dividend
* @param divisor
* @return
*/
public static int Divided2(int dividend, int divisor)
{
if(dividend ==0) return 0;
else if(divisor == 0 ) return Integer.MAX_VALUE;
int sign = 1;
if((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0) )
sign = -1;
long absdividen = Math.abs((long)dividend);
long absdivisor = Math.abs((long)divisor);
int result = 0;
long ans = 0;
while(absdivisor < absdividen)
{
long count = 1;
long temp = absdivisor;
while(temp < absdividen)
{
count <<= 1;
temp <<= 1;
}
ans += count >> 1;
absdividen -= temp>>1;
}
if(ans >Integer.MAX_VALUE )
result = (int)((sign == 1)? Integer.MAX_VALUE:Integer.MIN_VALUE);
else
{
result = (int)(sign * ans);
}
return result;
}