您的位置:首页 > 其它

leetcode笔记—二进制数中1的个数

2016-04-26 21:46 232 查看
基本思想:x=x&(x-1)可以消除x最右边的1;

1.给出一个32位的二进制数,统计其中1的个数

class Solution {
public:
int hammingWeight(uint32_t n) { //n=n&(n-1)可以消去最右边的1
int res=0;
while(n)
{
n=n&(n-1);
res++;
}
return res;
}
};

2.翻转一个32位数
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0; // 结果存放在这里
// 以下循环处理每个比特
for (int i = 0; i < 32; i++) {
// 取出输入的最后一位加入 result,其他位依次左移
result = (result << 1) | (n & 1);
n >>= 1; // 右移抛弃掉最后一位
}
return result;
}
};

3.给出数n,统计(0<=i<=n)i的二进制数中1的个数

class Solution {
public:
vector<int> countBits(int num) { //x&(x-1)可以消去最右边的1

vector<int> res;
for(int i=0;i<=num;i++)
{

res.push_back(incount(i));

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