题目简介
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.
题目的意思是计算一个无符号整形数的二进制中1的个数
自己的解法
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
int s = 2;
int y;
while(s != 0){
s = n/2;
y = n%2;
if(y == 1)
count++;
n = s;
}
return count;
}
}
you need to treat n as an unsigned value
坑爹呀,这道题并不是考察我们10进制转2进制,所以题目中给的是int而不是unsigned int,题目中任然让我们把它当做unsigned int.所以我的提交没有通过卡到了2147483648这个测试用例上。
Hot解法
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ones = 0;
while(n!=0) {
ones = ones + (n & 1);
n = n>>>1;
}
return ones;
}
}
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ones = 0;
while(n!=0) {
n = n & (n - 1);
ones++;
}
return ones;
}
}
n = 10100(二进制),则(n-1) = 10011 ==》n&(n-1) = 10000
可以看到原本最低位为1的那位变为0。
可以看到原本最低位为1的那位变为0。
在我们的题目中只要一直进行这一步操作,进行一次加一,知道这个数为0,也就计算出了当前数字二进制中1的个数.
参考http://blog.youkuaiyun.com/zheng0518/article/details/8882394(有关n = n & (n -1)的用法大家可以去看一下)
本文介绍并解析了解决无符号整型数二进制表示中1位计数问题的两种高效算法。首先通过直观的方法尝试将整数转换为二进制并计数零的个数,进而认识到题目的真正要求是将其视为无符号值处理,避免了不必要的转换步骤。接着引入了两种优化解法:一种是通过位运算直接计算,另一种则是利用位运算特性逐步消除最低位的1,直至数变为0,从而实现简洁高效的1位计数。文章还深入探讨了位运算中的关键操作原理及其应用价值。
386

被折叠的 条评论
为什么被折叠?



