1,题目要求
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11’ has binary representation;
00000000000000000000000000001011, so the function should return 3.
也就统计二进制数字中的1的个数-Hamming Weight
2,题目思路
一开始想直接通过逐位&来获得1的个数,但是这样操作的时间代价过于庞大了。
首先,STL中有内置的方法bitset,bitset是用来进行一些状态储存的操作。类似于一个标记数组,又类似于状压里面的二进制。
用法简介:
假设想要将int型数字,创建一个长度为32位的bitset,并统计其中1的个数:
int a = 3;
int counter = bitset<32>(a).count();
bitset基础用法+心得
用这种方法可以很简单的统计1的个数。
去除这种方法,还可以用n & (n-1)的方法,每次都去掉相对最低位的1,然后更新n,直到n为0(去掉所有的1)为止。
3,程序源码
class Solution {
public:
int hammingWeight(uint32_t n) {
return bitset<32>(n).count();
};
class Solution {
public:
int hammingWeight(uint32_t n) {
int res=0;
while(n)
{
n = n & (n-1);
res++;
}
return res;
}
};
uint8_t,uint16_t,uint32_t等都不是什么新的数据类型,它们只是使用typedef给类型起的别名,新瓶装老酒的把戏。不过,不要小看了typedef,它对于你代码的维护会有很好的作用。比如C中没有bool,于是在一个软件中,一些程序员使用int,一些程序员使用short,会比较混乱,最好就是用一个typedef来定义,如:
typedef char bool;一般来说,一个C的工程中一定要做一些这方面的工作,因为你会涉及到跨平台,不同的平台会有不同的字长,所以利用预编译和typedef可以让你最有效的维护你的代码。
按照posix标准,一般整形对应的*_t类型为:
1字节 uint8_t
2字节 uint16_t
4字节 uint32_t
8字节 uint64_t