0

I have this code that gets the binary representation of a number. I am trying to add up all the 1s that the number has. My problem is that when instead of adding up all the 1s it is just printing them out.

what I am trying to get

99 = 01100011

there are 4 1's


What am getting

there are 1111 1's


#include <iostream>
using namespace std;

int binary(int N)
{
    if (N == 0)
    {
        return 0;
    }
    else;
    {
        binary(N/2);
        int num = 0;
        if (N % 2 == 1)
        {
        num++; 
        cout<<num<<endl;
        }   
    }
}
int main()
{
int number;
cout << "Please enter a number that is greater or equal to 0: ";
cin >> number;
 binary(number);
 }      
DarkT
  • 169
  • 1
  • 4
  • 15

1 Answers1

1

I change your code in to this

#include <iostream>
using namespace std;

int binary(int N)
{
    static int num = 0;
    if (N != 0)
    {
        binary(N/2);

        if (N % 2 == 1)
        {
        num++; 

        }   
    }
    return num;
}
int main()
{
int number;
cout << "Please enter a number that is greater or equal to 0: ";
cin >> number;
cout <<  binary(number);
}
mhs
  • 1,012
  • 2
  • 14
  • 35