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

标签 c++ recursion binary

<分区>

我有这段代码可以获取数字的二进制表示形式。我正在尝试将数字所具有的所有 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);
}

关于c++ - 如何将数字的二进制表示中的所有 1 相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28469077/

相关文章:

recursion - 方案的简单步进代码

java - 二进制分隔距离 (Java)

c - 计算机中的整数表示 - C

javascript - 递归调用javascript函数

c++ - Blob ...如何非递归地写

ruby - 编码的十六进制字符串中的字节数

c# - C# 中的 std::string?

c++ - 将代码移动到头文件

python - Swig:如何将 c++ 字符串 const & 映射到 python 字符串?

c++ - 为什么在用花括号初始化结构时会出错?