题解 | #求int型正整数在内存中存储时1的个数#

求int型正整数在内存中存储时1的个数

http://www.nowcoder.com/practice/440f16e490a0404786865e99c6ad91c9

小结

BitSet即位图,是一个很长的“0/1”序列,他的功能就是存储0或者1。

bitset 转换成string,然后find出1的个数

using namespace std;
int main()
{
    int in_n;
    while(cin >> in_n)
    {
        bitset<32> b0(in_n);
        string s = b0.to_string();
        // 输出二进制
        int count = 0;
        size_t pos = s.find("1");
        while(pos!=s.npos)
        {
            count++;
            s =s.substr(1+pos,s.size());
            pos = s.find("1");
        }
        cout << count << endl;
    }
    return 0;
}
全部评论

相关推荐

2025-12-03 03:32
安徽大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务