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.
For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should return 3.
Hide Tags :Bit Manipulation
解题思路:
思路一:最直接的方法就是不断 mod 2 判断是不是 1 ,但是在leetcode的OJ测试时,当n=2147483648时就会报错,后来百度一下知道,输入的n是正整数32bit,也就是无符号的,java的int是有符号的,也就是说32bit里还包含负数,当然输入2147483648时就超出你的输入参数的范围啦。(OJ检查失败)
代码如下:
public static int hammingWeight(int n)
{
int remain=0;
int count=0;
if (n==0)
{
return 0;
}
else
{
while (n!=0)
{
remain=n%2;
n=n/2;
if (remain==1)
{
count++;
}
}
return count;
}
}
思路二:基本与思路一类似,只是采用的形式不一样,引入了“位运算”,即每次将n>>1(向右移动一位)然后同1进行&(与运算),这个思路当输入i是正数时没有问题,与思路一类似,但当输入的n是一个负数时,不但不能得到正确的1的个数,还会进入死循环。(OJ检查失败)
代码如下:
<span style="white-space:pre"> </span>public static int hammingWeiht2(int n)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>int count=0;
<span style="white-space:pre"> </span>while (n!=0)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>if ((n&1)!=0)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>count++;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>n=n>>1;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>return count;
<span style="white-space:pre"> </span>}
思路三:在思路二的方法上得到启发,既然需要进行比较的值不能进行移位,那可以将1向左进行移位 ,设置一个标志 flag=1,
flag=flag<<1 (比较一次以后左移一位),然后flag&n进行“与”运算。(OJ检查成功)
代码如下:
<span style="white-space:pre"> </span>public static int hammingWeiht3(int n)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>int count=0;
<span style="white-space:pre"> </span>int flag=1;
<span style="white-space:pre"> </span>while (flag!=0)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>if ((flag&n)!=0)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>count++;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>flag=flag<<1;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>return count;
<span style="white-space:pre"> </span>}
思路四(推荐):
可以引入
汉明重量
,基于一种事实即 X 与 X-1 位与得到的最低位永远是 0。(OJ检查成功)
例如:
Expression | Value |
X | 0 1 0 0 0 1 0 0 0 1 0 0 0 0 |
X-1 | 0 1 0 0 0 1 0 0 0 0 1 1 1 1 |
X & (X-1) | 0 1 0 0 0 1 0 0 0 0 0 0 0 0 |
减 1 操作将最右边的符号从 0 变到 1,从 1 变到 0。这样操作之后的直接结果是,原数少了个1位。而且对于负数也同样有循环终点。
代码如下:
public static int hammingWeight1(int n)
{
int count=0;
while (n!=0)
{
n=n&(n-1);
count++;
}
return count;
}