NVIDIA Interview Question
Software Engineer / DevelopersCountry: United States
/* Compile and Executed this code in Linux GCC 3.2*/
#include <stdio.h>
int count(int n)
{
int i=0;
if(n==0)
return 0;
else
{
while (n>0)
{
if(n&1)
++i;
n>>=1;
}
return i;
}
}
int main()
{
int n;
printf ("Enter no\n");
scanf ("%d",&n);
printf ("no of bit that are 1 one in this number is %d\n",count(n));
return 0;
}
One of the very basic implementations of the above algorithm is to use the & operator to & it with the number 1 to check if the current bit is 1 or not if yes then increment the count variable else skip the bit and then right shift the bit.
Implementation:
#include<bits/stdc++.h>
using namespace std;
void countbits(int x){
int count = 0;
while(x){
if(x & 1 == 1)
count++;
x = x >> 1;
}
return count;
}
Good enough
- = November 14, 2013