天天看點

LeetCode 191 Number of 1 Bits(1 比特的數字們)

版權聲明:轉載請聯系本人,感謝配合!本站位址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50506429

翻譯

寫一個函數擷取一個無符号整型數,并且傳回它的“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;
    }
};           

繼續閱讀