Java Code Geeks

Thursday, January 15, 2009

Job interview question Part 1

public static int getCountOfOnes(int n) {
/*
Please implement this method to
return the number of '1's in the binary representation of n
for any integer n, where n > 0

Example: for n=6 the binary representation is '110' and the
number of '1's in that
representation is 2

*/
int count = 0;
int a = 1;

for (int i=1 ; i < 31; i++)
{
int val = n & a ;
if (val > 0 )
count++;
a = a << 1;
}

return count;
}


This is an ideal question to find out whether the developer is aware of bitwise operators ... logic is to perform bitwise and and see the value. If the value if more than 0, then that position contains 1.
Example 6 = 110
Perfor bitwise & with 1, result is 110 & 001 = 0 so there is no 1 at this position
bitwise & with 2 (10), result is 110 & 010 = 010 so there is one 1 at the second positions etc..

No comments: