LeetCode191:Number of 1 Bits【Java】

原题目:
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;
    }
}
```
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值