寫一個函數獲取一個無符號整型數,並且返回它的“1”比特的數目(也被叫做Hamming weight)。
例如,一個32位整型數“11”,轉換成二進制是00000000000000000000000000001011,所以這個函數應該返回3。
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.
這道題我之前遇到過,這裡就直接貼結果了,稍候我整理一篇關於位運算的博客出來。歡迎大家再來……
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while (n) {
++count;
n = (n - 1) & n;
}
return count;
}
};