如何将数字的二进制表示中的所有 1 相加

How to add up all the 1s in a binary representation of a number

我有这段代码可以获取数字的二进制表示形式。我正在尝试将数字所具有的所有 1 相加。我的问题是,当不是将所有 1 相加时,它只是将它们打印出来。

我想得到什么

99 = 01100011

有 4 个 1


我得到了什么

有 1111 个 1


#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);
 }      

我把你的代码改成这个

#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);
}