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;
}
};
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;
}
};
相关文章推荐
- sed 笔记(三)
- 小甲鱼PE详解之基址重定位详解(PE详解10)
- angularjs 动态生成多个checkboxs,但只能选择一个
- JSON
- Android 开源框架Universal-Image-Loader完全解析(一)--- 基本介绍及使用
- c++作业4
- 网站构建前期知识掌握
- 数字证书原理,公钥私钥加密原理
- c++第四次作业
- Ubuntu上安装 Emacs 24的几种方法
- 蓝牙介绍
- LeetCode 3, Longest Substring Without Repeating Characters
- 多益网络2016春季实习校招笔试回顾(C++游戏后台开发)
- 2016多益网络春季实习校园招聘笔试回顾(C++游戏后台开发)
- Sort a linked list using insertion sort
- 登录phpMyAdmin出现密码不正确问题
- 好用的安卓抓包工具-Fiddler
- 浅谈requireJS
- VB.NET基础之DLL
- Nginx虚拟主机配置教程