Problem
Divide two integers without using multiplication, division and mod operator.
Code
int absval(int num,int bits)
{
int mask = num>>bits;
return ((num + mask)^mask);
}
bool isDivNegative(int n1,int n2,int bits)
{
int mask = 1 << bits;
return ((n1 & mask) ^ (n2 & mask));
}
int division(unsigned int n1,unsigned int n2,int bits) {
unsigned int q = 0;
unsigned int r = 0;
for(int i = bits;i >= 0; --i){
r = r << 1;
if(n1 & (1 << i))
r |= 1;
else
r &= ~1;
if(r >= n2){
r -= n2;
q |= (1 << i);
}
}
return q;
}
int divide(int dividend, int divisor) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int bits = numeric_limits<int>::digits;
unsigned int n1 = absval(dividend,bits);
unsigned int n2 = absval(divisor,bits);
int ret = division(n1,n2,bits);
return ((isDivNegative(dividend,divisor,bits)) ? -ret : ret);
}
No comments:
Post a Comment