Counting setbits of number from 1 to N (Asked in Amazon)
#include<stdio.h>
#include<conio.h>
int countSetBitsUtil(int);
int main(){
int i;
int count=0;
int n;
scanf("%d",&n);
for(i=1;i<=n;i++){
count+=countSetBitsUtil(i);
}
printf("%d",count);
}
int countSetBitsUtil(int i){
int counter=0;
while(i>=1){
if(i%2==1){
counter++;
}
i=i/2;
}
return counter;
}
This method is for only beginners. Stay tuned for the Optimum solution...
Comments
Post a Comment