您的位置:首页 > 其它

191. Number of 1 Bits

2016-05-19 12:00 239 查看
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.

思路:愚蠢如我,一开始只想到把十进制转换成二进制然后数数。后来又想利用2^n-1的规律。

然后一看答案直接给跪。

n&n-1,就是这么简单。每次n&n-1都会去掉一个1。

tips: 关于uint32_t:uint8_t,uint16_t,uint32_t等都不是什么新的数据类型,它们只是使用typedef给类型起的别名,新瓶装老酒的把戏。

class Solution {
public:
int hammingWeight(uint32_t n) {
int res=0;
while(n){
n&=n-1;
res++;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: