Number of 1s in a binary number

Viewed 178

I need to make a program that counts the number of 1s in the binary representation of an unsigned number, using a recursive function, so this is my code:

#include <stdio.h>
#include <stdlib.h>

int one(unsigned n);

int main()
{
    unsigned n;
    printf("n= "); scanf("%u", &n);
    printf("%d", one(n));

    printf("\n");
    return 0;
}

int one(unsigned n)
{
    if(n==1 || n==0)
        return n;
    else
        return (n&1+one(n>>1));
}

Thing is, my code works for number 7 for example, but if I enter the number 2 it will print that it has 2 ones in it. And for 4 it returns 0, and I think for all exponents of 2 it returns 0 in the end. I can't figure out why.

3 Answers
Related