[LeetCode]Number of 1 Bits

Question

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.


本题难度Easy。有2种算法分别是: 移位法 和 减一相与法

1、移位法

复杂度

时间 O(N) 空间 O(1)

思路

通过与运算符判断最低位/最高位是否是1,然后再右移/左移。重复此步骤直到原数归零。

代码

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        //require
        int ans=0;
        //invariant
        for(int i=0;i<32;i++){
            if((n&1)==1)ans++;
            n>>=1;  
        }
        //ensure
        return ans;
    }
}

注意

这道题说的是把n当作 unsigned integer,但是n仍然是signed integer。第9行写为>>>,循环条件可以写成while(n!=0)

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int mark = 0b1, count = 0;
        while(n != 0b0){
            if((n & mark)==0b1){
                count++;
            }
            n >>>= 1;
        }
        return count;
    }
}

但是第9行写为>>,循环条件就不可是while(n!=0)。为简化假设n只有4位,第1位为符号位,令n=-3,二进制就是1101,那么进行n>>=1后得到的二进制结果为1110(符号位右移了,但是符号位不会变成0),所以要注意。

参见:Java整数占几个字节,以及负数的二进制表示方法,以及Java的逻辑运算符>>和>>>的区别

2、减一相与法

复杂度

时间 O(N) 空间 O(1)

思路

该方法又叫Brian Kernighan方法。当n不为0时,n = n & (n - 1);。因为每次减一如果最右边有1那么消除右边的1,所以消去几次就有几个1。
比如:

  • 011,减去1得010,相与得010,消去了最右边的1
  • 110,减去1得101,相与得100,消去了最右边的1

代码

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        while(n != 0){
            n = n & (n - 1);
            count++;
        }
        return count;
    }
}

参考

[Leetcode] Number of 1 Bits 一的位数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值