Reputation: 69
I have to divide two numbers by just using the bitwise operators. My code is as follows:
public class Solution {
public int divide(int dividend, int divisor) {
int c = 0, sign = 0;
if (dividend < 0) {
dividend = negate(dividend);
sign^=1;
}
if (divisor < 0) {
divisor = negate(divisor);
sign^=1;
}
if ( divisor != 0){
while (dividend >= divisor){
dividend = sub(dividend, divisor);
c++;
}
}
if (sign == 1){
c = negate(c);
}
return c;
}
private int negate(int number){
return add(~number,1);
}
private int sub(int x, int y){
return add(x,negate(y));
}
private int add(int x, int y){
while ( y != 0){
int carry = x&y;
x = x^y;
y = carry << 1;
}
return x;
}
}
I am getting a time out exception while running the code :
Last executed input:
2147483647
1
I added an extra check in the code like this :
if (divisor == 1){
return dividend;
}
but then on running the code again, I am getting a Time out exception like this:
Last executed input:
2147483647
2
Can you help me where I am going wrong with the code?
Upvotes: 0
Views: 1632
Reputation: 49804
Think of how long division works, the pen-and-paper method for division we've all learnt at school.
Of course we've learnt it in base 10, but is there any reason why the same algorithm wouldn't work in base 2?
No, in fact it's easier because when you're doing the division step for each digit, the result is simply 1 if the part of the dividend above the divisor is greater than or equal to the divisor, and 0 otherwise.
And shifting the divisor and the result come out of the box too.
Upvotes: 0
Reputation: 474
Since you are using a naïve implementation of the arithmetical operations, I assume it just takes too long, since it has to do roughly 1 billion of subtractions, each of which is a loop of 16 iterations on average. So it'd be about 5 seconds on a 3GHz CPU, if every inner step took 1 cycle. But since it obviously takes more, especially considering it's in java, I'd say you can easily expect something like a 1 minute running time. Perhaps java has a timeout check for the environment you are running it in.
I have to admit I haven't thoroughly verified your code and assumed it worked correctly algorithm-wise.
Upvotes: 0