题目
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Example:
Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011
解法
思路
这道题和leetcode]190.Reverse Bits一样,都是关于位运算的题目,思路很简单,用countOne来计数,如果n的最后一位是1,则countOne加一。然后将n右移一位。
代码
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int countOne = 0;
for(int i = 0; i < 32; i++) {
countOne += (n&1);
n >>= 1;
}
return countOne;
}
}