Cognzant Technology Solutions Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
@second anonymous: i really don't know what to say to you. you are aware that functions don't just magically exist, that they have to be implemented somehow before they exist?
That's a good one! I was going to solve it less efficiently with something like:
int mask = v >> (sizeof(int) * CHAR_BIT - 1);
return ( (-v) & mask) + (v & ~mask);
Explanation: when v is negative, mask is 11111....1111 and ~mask is 00000...0000. All the bits of (-v) will be kept and none of the bits of v, so we'll get -v + 0 = -v. When v is positive or zero, the mask is 00000...0000 and ~mask is 11111...1111, which means all bits of -v are discarded, and all the bits of v are kept. So we get 0 + v = v.
-v when v < 0
v when v >= 0
That's the definition of absolute value.
What about try-catch?
public int abs(int n)
{
try{
int a = int.MaxValue + n;
return -n; //if it gets here, n is negative
}
catch{
return n; //if gets here, n is positive
}
}
int v; // we want to find the absolute value of v
- fresherparty September 10, 2012unsigned int r; // the result goes here
int const mask = v >> sizeof(int) * CHAR_BIT - 1;
r = (v + mask) ^ mask;
Reference: graphics.stanford.edu/~seander/bithacks.html#IntegerAbs
You can also watch this video to understand this solution
youtube.com/watch?v=zJGts7hOX9s