Q10. How to fast multiply a number by 4?

Bitwise operations are slightly faster than addition and subtraction operations and usually significantly faster than multiplication and division operations. Because bit wise operation is performed with in one register, and other arithmetic instructions needed to handle more then one registers.

So a number shifted left by one bit means, number multiplied by 2.

num << 2  is equivalent to num * 4, but first operation is faster than  second one

Suppose interviewer asked how to fast multiply a number by 9?

(num << 3) + num

This is same as

(num * 8) + num = num * (8+1) = num  * 9

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.