Qualcomm Interview Question
Software Engineer / DevelopersI think there is some thing very wrong with your code, coz your bitwise anding a no with it's previous no.
Eg if i've to check no of 1's in n=8 then according to your logic n=n&(n-1) would give 0 i would become 1. Then after that control would exit the loop, because of condition while(n) as n would get changed to a ZERO.
Try to alter the code or check each bit.
i think naga's code works just fine...@someone...if you take the example of 8 then you are right after the first iteration the number becomes 0 and that is the desired outcome because 8 will contain only one "1".
Here is something that works with both negative and positive numbers --
int number_of_bits(int input)
{
int nAnder = 1;
int nCount = 0;
while( nAnder )
{
if( input & nAnder )
nCount++;
nAnder = nAnder << 1;
}
return nCount;
}
int numberOf1s(int n)
{
int count = 0;
if(n==0)return count;
while(n&=n-1)count++;
return ++count;
}
void main()
{
printf("%d",numberOf1s(7));
}
Output: 3
Works even for negative numbers, tried it!
One of the easy approaches of the above algorithm is to check when the & operation of the given number with 1 is 1 because at that case only 1 bit will be the number where this condition is satisfied and elsewhere it will be 0 so, at the former case increment the counter variable and at the end return the count
Implementation:
#include<bits/stdc++.h>
using namespace std;
int countbits(int n){
int count = 0;
if(n == 0)
return 0;
while(n){
if(n&1 == 1)
count++;
n = n>>1;
}
return count;
}
int i=0;
- Naga Samrat Chowdary, Narla May 11, 2010while (n){
n=n&(n-1);
i++;}
return i;
Thanks!