题目要求
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
输入输出
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。
题目思路
采用二进制计算方式:
对n和n-1进行按位与计算
当n与n-1进行按位与计算时 相当于将n的最右边的1换为0 则记录一次数值
直至n为零则再无1
代码
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int countx = 0;
while(n != 0) {
countx++;
n = n & (n-1);
}
return countx;
}
}
方法二:将n的每位都和1进行与运算 结果不为零的累加
题目来源
leetcode
https://leetcode-cn.com/problems/number-of-1-bits/
涉及知识
位运算:
左移1位 乘2 101<<1 = 1010 5->10
右移1位 除2 1010>>1 = 101 10->5