Recursively find 1s in binary

Hi, I am writing a program to help me find the number of 1's in binary representation of a number. Using recursion was one of the requirements. However, when I run this program, for example , when I input 8, I expect to get

temp 1+ findBits&1 0 = numBits 1;
temp 1+ findBits&1 0 = numBits 1;
temp 1+ findBits&1 0 = numBits 1;
number of ones: 1

but instead this is what it outputs

temp 1+ findBits&1 0 = numBits 2;
temp 2+ findBits&1 0 = numBits 0;
temp 0+ findBits&1 0 = numBits 0;
number of ones: 0


Here is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 #include <iostream>


using namespace std;


int numberBits(int findBits) {
int numBits;
    if (findBits==1||findBits==0) {
        numBits=0;
        numBits=numBits+findBits&1;
        return numBits;
    }
    int passOn=findBits>>1;
    int temp=numberBits(passOn);
    numBits=findBits&1+temp;
    int temp2=findBits&1;
    cout << "temp " << temp << "+ findBits&1 " << temp2 << " = " <<
    "numBits " << numBits << endl;
    return numBits;
}
int input;
int main()
{
    cin >> input;
    cout << "number of ones: " << numberBits(input);
    return 0;
}
Last edited on
In: numBits=findBits&1+temp;, does & have higher precedence or +?

[edit: And by the way, pick some better names. temp and temp2?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int numberBits(int value) {
    if (value < 2) {
        return value;
    }

    int shifted_value = value >> 1;
    int bits_in_shifted = numberBits(shifted_value);

    int lsb = value & 1;
    int num_bits = lsb + bits_in_shifted;

    // cout << bits_in_shifted << " + " << lsb << " = " << num_bits << endl;

    return num_bits;
}

]
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int countBits(unsigned long n) {
    if (n == 0) return 0;
    return (n & 1) + countBits(n >> 1);
}

int main() {
    unsigned long n;
    std::cout << "Enter a positive integer: ";
    std::cin >> n;
    std::cout << "Number of 1 bits: " << countBits(n);
    return 0;
}

Last edited on
Topic archived. No new replies allowed.