Number of 1 Bits
2015-12-04 19:53
309 查看
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
so the function should return 3.
目的是判断一个数字的二进制中有点多少个1,
我们可以通过数字的二进制右移的性质进行判断,判断数字的最后一位是不是1,如果是则进行相加:
直到数字为0
class Solution {
public:
int hammingWeight(uint32_t n) {
int result=0;
int move;
while(n!=0){
move=n& 0x1;
result=result+move;
n=n>>1;
}
return result;
}
};
n = 0x110100 n-1 = 0x110011 n&(n - 1) = 0x110000
n = 0x110000 n-1 = 0x101111 n&(n - 1) = 0x100000
n = 0x100000 n-1 = 0x011111 n&(n - 1) = 0x0
看到这里已经得到了一种新的解法,n中本来有3个1,按照此种思路只需要循环3此即可求出最终结果,
n&(n-1)用于求解n中1的个数,每次n&(n-1)就是消去数字末尾中的1,,通过循环我们可以直到数字中有多少个二进制1,、
class Solution {
public:
int hammingWeight(uint32_t n) {
int result=0;
while(n!=0){
n=n&(n-1);
result++;
}
return result;
}
};
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011,
so the function should return 3.
目的是判断一个数字的二进制中有点多少个1,
我们可以通过数字的二进制右移的性质进行判断,判断数字的最后一位是不是1,如果是则进行相加:
直到数字为0
class Solution {
public:
int hammingWeight(uint32_t n) {
int result=0;
int move;
while(n!=0){
move=n& 0x1;
result=result+move;
n=n>>1;
}
return result;
}
};
n = 0x110100 n-1 = 0x110011 n&(n - 1) = 0x110000
n = 0x110000 n-1 = 0x101111 n&(n - 1) = 0x100000
n = 0x100000 n-1 = 0x011111 n&(n - 1) = 0x0
看到这里已经得到了一种新的解法,n中本来有3个1,按照此种思路只需要循环3此即可求出最终结果,
n&(n-1)用于求解n中1的个数,每次n&(n-1)就是消去数字末尾中的1,,通过循环我们可以直到数字中有多少个二进制1,、
class Solution {
public:
int hammingWeight(uint32_t n) {
int result=0;
while(n!=0){
n=n&(n-1);
result++;
}
return result;
}
};
相关文章推荐
- html分页实现
- iOS 9人机界面指南:iOS 技术 (3D Touch、Live Photos、Wallet以及Apple Pay)
- Windows Server 2012 配置远程桌面帐户允许多用户同时登录
- 关于鼠标长按的代码
- Specify compute hosts with SSDs
- Minimum Inversion Number(线段树求逆序数)
- SVN的问题
- hdoj f(n) 2582 (GCD打表&找规律)好题
- hud3108--Ant Trip
- Android打包程序
- Shell命令sshpass非交互SSH密码验证
- 把事情往苦逼里做
- Oracle12c学习(二)---Linux下SQL Developer 安装
- Android LocalSocket与Socket 区别
- 关于UI适配的文档
- PHP图片等比缩放,并添加Logo水印特定代码和盯
- UVA 11624 两次bfs搞搞
- 黑马程序员之System、Runtime、Math、Date、Calendar类
- UITextView 光标定位
- 【PA2014】【BZOJ3727】Zadanie