原题目:
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,这里用位操作很容易解且效率高,不过我刚开始用的是手工计算的思路,也就是之前我们手动进行计算的除以2余1来进行计算的,结果效率很低,超出了LeetCode的时间限制,代码如下:
code1:低效代码
```java
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(long n) {
int[] bit = new int[32];
int i =0;
int re = 0;
if(n==0){
return 0;
}else if(n==1){
return 1;
}else{
while(n!=2){
if(n%2!=0){
bit[i]=1;
}
n = n/2;
i++;
}
bit[i+1]=1;
for(int y = 0;y<32;y++){
if(bit[y]==1){
re++;
}
}
return re;
}
}
}
```
再看另一个思路:
首先我们看如下规律:
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&n-1知道n=0时的计算次数就是1的个数,那么我们得到如下代码
code2:位计算高效率代码
```java
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int result = 0;
while(0!=n){
n = n&(n-1);
result++;
}
return result;
}
}
```