Wednesday, December 08, 2004

C/C++ : Multiply x by 7 without using multiplication (*) operator.

This one is easy. I came up with several solutions:

Solution 1:
return (x + x + x + x + x + x + x);

Solution 2:
return (x << 3) – x;

Solution 3:
return (x << 2) + (x << 1) + x;

However solution 2 and solution 3 only work for integers. What if the number is not an integer? How about this one?

Solution 4:
return x/(1/7.0);

0 Comments:

Post a Comment

<< Home