LeetCode题解之Number of 1 Bits

1、题目描述

2.问题分析

使用C++ 标准库的 bitset 类,将整数转换为 二进制,然后将二进制表示转换为字符串,统计字符串中 1 的个数即可。

3、代码

 1 int hammingWeight(uint32_t n) {
 2         bitset<32> b(n);
 3         string b_s = b.to_string() ;
 4         
 5         int count_one = 0;
 6         for(string::iterator it = b_s.begin(); it != b_s.end() ; ++it )
 7         {
 8             if( *it == '1')
 9                 ++count_one;
10         }
11         return count_one;
12     }
pp
原文地址:https://www.cnblogs.com/wangxiaoyong/p/9295660.html