二进制表示 [英] binary representation

查看:131
本文介绍了二进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,sum(6)必须返回2,因为6的二进制版本是110

For example,sum(6) must return 2, because the binary version of 6 is 110

不确定逻辑是否正确。

not sure the logic is correct or not.

int sum(int n)
{
    int count = 0;
    while(n)
    {
        count += n & 1;
        n >>= 1;
    }
    return count;
}
int main(){
    int n   =   9001;
    cout << "The    sum of  bits    for number  "   <<  n   <<  "is"    <<  sum(n)  <<  endl;
    retun   0;
}


推荐答案

解决这些问题是使用标准库。

As ever, the best way to tackle these problems is to use the standard library. You have all studied the tools available in the standard library, right?

; - )

#include <iostream>
#include <bitset>


template<class T>
size_t bits_in(T t)
{
    return std::bitset<sizeof(t) * 8>(t).count();
}

int main()
{
    using namespace std;
    int i = 6;

    cout << "bits in " << i << " : " << bits_in(i) << endl;

    long l = 6353737;
    cout << "bits in " << l << " : " << bits_in(l) << endl;

    return 0;
}

预期输出:

bits in 6 : 2
bits in 6353737 : 11

这篇关于二进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆