# 191. Number of 1 Bits 位1的个数

@TOC

[LeetCode]

Total Accepted: 88721 Total Submissions: 236174 Difficulty: Easy

## # 题目描述

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

Example 1:

``````Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011
``````

Example 2:

``````Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000
``````

## # 解题方法

### # 右移32次

``````>>是符号位保持不变的右移。
``````

``````public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
while(n!=0){
n>>>=1;
}
}
}
``````

AC:2ms

### # 计算末尾的1的个数

LeetCode给出的另一种巧妙解法。

``````public int hammingWeight(int n) {
int sum = 0;
while (n != 0) {
sum++;
n &= (n - 1);
}
return sum;
}
``````

python代码如下：

``````class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
res = 0
while n:
res += 1
n &= n - 1
return res
``````

### # 转成二进制统计1的个数

``````class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return bin(n).count("1")
``````

``````class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""