0
点赞
收藏
分享

微信扫一扫

位运算的算法(持续更新...)

热爱生活的我一雷广琴 2022-04-05 阅读 45
java

有关位运算的算法

位1的个数(汉明重量)

编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘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-1);
            count++;
        }
        return count;
    }
}
举报

相关推荐

0 条评论