Qualcomm Interview Question
Software Engineer / DevelopersMost optimal solution would be -
int num /* given 16 bit integer */
int count = 0; /* total no. of 1's in num */
while (num & (num-1)) {
count++;
num = num & (num-1);
}
print(++count);
The number of 1s in the given number can be found by right shifting the binary number of the given integer and counting the number of 1s if it satisfies the condition that (n&1 == 1) else it is not a set bit.
Implementation:
{int findone(int n){
int count = 0;
while(n>0){
if(n&1 == 1)
count++;
n = n << 1;
}
return count;
}
int num /*Given 16 bit integer*/
- Anonymous March 07, 2010int count = 0; /*gives total no. of 1's in num*/
for(i=0;i<16;i++)
{
if((num>>i) && 1)
{
count++;
}
}