Leetcode[191] Number of 1 Bits
16 Nov 2015###Task1 Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.
###Python
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
ret = 0
for i in range(32):
cur = (n >> i) & 1
if cur == 1:
ret += 1
return ret
###Java
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
for (int i = 0; i < 32; i++) {
if ((n & 1) == 1) {
count++;
}
n = n >> 1;
}
return count;
}
}
###Points
- (n » a) & 1 –> get one bit
- n ^ (1 « a) –> rotate one bit
- 输入值n可能为负数(但应视其为无符号整数,但Java中实际上是没有无符号整数的)
- 使用无符号右移操作,可以忽略符号位。