I have written recursive function which will return me the count of number of one bits from a given number. Whenever I try to run the code, it says segmentation fault core dump. Please tell me what’s going wrong in this code??
#include<stdio.h>
int main(){
int no;
printf("Enter the number:\n");
scanf("%d",&no);
printf("Count of Number of One Bits is:%d\n",recursiveCountNumberOfOnes(no));
//recursiveCountNumberOfOnes(no);
}
int recursiveCountNumberOfOnes(int no){
int x=1;
int count=0;
if((no&x)!=0)
{
count++;
x=x<<1;
}
return recursiveCountNumberOfOnes(count);
}
Here's a simple way to do it for unsigned integers. Notice how it just returns 1 +
each time a bit is set, and continues to recurse as long as no
is not zero. Finally adding in a zero at the end.
int recursiveCountNumberOfOnes(unsigned int no)
{
if (no&1)
return 1 + recursiveCountNumberOfOnes(no>>1);
else if (no)
return recursiveCountNumberOfOnes(no>>1);
else
return 0;
}
And a slightly golfier version
int recursiveCountNumberOfOnes(unsigned n) {
return n?(n&1)+recursiveCountNumberOfOnes(n/2):0;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments