Wednesday, 3 July 2013

Given a number, return the next multiple of 64 that follows it, using bit operations and no loops. e.g input = 90, return 128.


#include <iostream>
using namespace std;

int main()
{
    int n = 90;
    int n1 = n>>6;
    int n2 = (n1+1)<<6;
    cout<<n2;
    system("pause");
}

3 comments:

  1. Hi Varun,

    Thanks for this post. I trust you will understand this criticism: a solution on it's own does not help us understand what was your thought process. For all I care you could have printed 128 and get away with it.

    You will also often find that interviewers want to know how you got to that code. Can you explain exactly what is going on in there Varun?

    Thanks

    ReplyDelete
  2. Hey

    Thanks for writing, I usually post the algorithms and explanation along with the code sorry I missed it for few.

    Well its too easy, the above code is equivalent to below:
    n1=n/64;
    n2= (n1+1)*64

    eg n = 90.
    n1 = 90/64 = 1.
    n2 = (n1+1)*64 = (1+1) * 64 = 128.

    I have used ">>" and "<<" bit shift operators for division and multiplication by 64 as they are very fast as compare to division and multiplication operations.

    ReplyDelete