Tuesday, November 1, 2011

Quickly multiply with 7

Give a fast method to multiply a number by 7.

Solution :
  1. We multiply by 7 by first multiplying by 8 and subtracting the number from the result.
  2. Multiplication by 8 is equivalent to shifting left 3 bits.
Complexity  :
  • Time : O(1)
  • Space : O(1)
Code  :

int multiply_7(int N){
return (N << 3) - N;
}

No comments:

Post a Comment