Back to Blog

Interview: Clever Use of Binary

#Binary#BitManipulation#InterviewQuestion#Programming
  1. Determine the return value of the following function (Microsoft)
int func( x )
{
    int countx = 0;
    while(x)
    {
        countx ++;
        x = x&(x-1);
    }
    return countx;
}

Approach: Convert x to its binary representation and count the number of set bits (1s).

For example, if x=6, the answer is 2;

If x=9999, the answer is 8.