Divide two integers without using multiplication, division and mod operator.
Solution:
1st solution: use the add/subtraction method, but which can not pass the big OJ, such as the input is :2147483647, 1
running time: O(n).
public class Solution {
public int divide(int dividend, int divisor) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int sign = 1;
if(dividend < 0){
sign *= -1;
}
if(divisor < 0){
sign *= -1;
}
long tempDividend = Math.abs(dividend);
long tempDivisor = Math.abs(divisor);
int count = 0;
while(tempDividend - tempDivisor >= 0){
count++;
tempDividend = tempDividend - tempDivisor;
}
return count * sign;
}
}
2nd solution:
optimize the 1st solution, double the divisor each time.
Running Time: O(lg(n));
note: there's two while loop here, if the temp_divisor bigger than the current dividend, set the temp_divisor to the initial value and start the loop again.
public class Solution {
public int divide(int dividend, int divisor) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int sign = 1;
if(dividend < 0){
sign *= -1;
}
if(divisor < 0){
sign *= -1;
}
long a = dividend;
long b = divisor;
//must cast to long here for dealing with the Integer.MIN_VALUE
//because Math.abs(-2147483648) > Integer.MAX_VALUE
a = Math.abs(a);
b = Math.abs(b);
int count = 0;
while(a >= b){
long temp = b;
int multi = 1;
while(a >= temp){
count += multi;
a -= temp;
temp += temp;
multi += multi;
}
}
return count * sign;
}
}
3rd solution: use the bit manipulation, similar to the 2nd solution. To be continued...
running time: O(lg(n)).
4th solution: math formular: exp(log(a) - log(b)); To be continued...