Amazon Interview Question
Software Engineer / DevelopersIf u shift the bits 3 times, u r multiplying the number by 2^3 = 8. so now subtract the number by itself to multiply it by 7 times.
Say you have to multiply 'a' by 'b'.
Find a smallest number 'c' which is greater than 'b' and is a power of 2 (you would be interested in this because you would want to shift bits - efficient method.) so if c = 2^k then a.c = (a << k) right shifting 'a' by k bits.
Now, we know that a.c is greater than a.b, so we would want to subtract the difference [(c-b).n] off the *product*,
simply put: b = ( c - delta ) -> a.b = (c-delta) . a -> a.b = a.c - a.delta
[delta is known in all cases since you pick 'c' and 'b' is already given]
int multBy7(unsigned int n)
- Anonymous March 11, 2010{
return ((n<<3) - n);
}