您的位置:首页 > 其它

[Leetcode] #191 Number of 1 Bits

2017-02-16 15:21 405 查看

Discription:

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.

Solution:

#include <stdint.h>
int hammingWeight(uint32_t n) {  //负数会溢出
int count = 0;
while (n){
if (n & 1)
count++;
n = n >> 1;
}
return count;
}
int hammingWeight(uint32_t n) {  //循环次数变多
int count = 0;
uint32_t a = 1;
while (a){
if (n & a)
count++;
a <<= 1;
}
return count;
}
int hammingWeight(uint32_t n) {  //比较好的方法
int count = 0;
while (n){
n = n&(n - 1);
count++;
}
return count;
}

GitHub-Leetcode:https://github.com/wenwu313/LeetCode

位运算相关参考:https://leetcode.com/problems/sum-of-two-integers/?tab=Solutions
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: