# C#LeetCode刷题之#191-位1的个数（Number of 1 Bits）

Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

Input: 11

Output: 3

Explanation: Integer 11 has binary representation 00000000000000000000000000001011

Input: 128

Output: 1

Explanation: Integer 128 has binary representation 00000000000000000000000010000000

```public class Program {

public static void Main(string[] args) {
var n = 11U;

var res = HammingWeight(n);
Console.WriteLine(res);

n = 128U;

res = HammingWeight2(n);
Console.WriteLine(res);

}

public static int HammingWeight(uint n) {
//10进制转2进制，除2取余法
var count = 0;
while(n != 0) {
if(n % 2 != 0) count++;
n /= 2;
}
return count;
}

public static int HammingWeight2(uint n) {
//基本思路同 HammingWeight
var count = 0;
while(n != 0) {
//10进制的1，2，3，4，5对应于2进制的1，10，11，100，101
//由于2进制的特点，末位数在1，0之间循环
//用 n 和 1 做“与运算”若值为1，必为奇数
//即除2余1
if((n & 1) == 1) count++;
//2进制右移1位即10进制除2
n >>= 1;
}
return count;
}

}```

```3
1```