1332. 判断一个整数中有多少个1
写一个函数,其以无符号整数为输入,而输出它所具有的“1”的位数(也被称为汉明权重)
样例
样例 1
输入:n = 11
输出:3
解析:11(10) = 1011(2), 返回 3
样例 2
输入:n = 7
输出:3
解析:7(10) = 111(2), 返回 3
public class Solution {
/**
* @param n: an unsigned integer
* @return: the number of ’1' bits
*/
public int hammingWeight(int n) {
// write your code here
int count = 0;
while(n>0){
n = n&(n-1);
count++;
}
return count;
}
}