(LeetCode 191) Number of 1 Bits

題:
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.

也是就輸入一個無符號整數,對其二進制裏面的1進行計數。

solution:
這道題主要一個陷阱就是,題目要求計算的是該整數無符號二進制中的1的個數,但是整數實際上在計算機中是按照有符號二進制補碼存儲會有一位符號位,所以當輸入爲231 時,其無符號二進制是100000000000000000000000000000000,但是你轉換出來是011111111111111111111111111111111,因爲溢出了.
我們只需要把輸入的32位無符號整數用long類型存儲,這樣可以避免數據位被轉化成符號位。

class Solution {
public:
    int hammingWeight(uint32_t n) {
        long m = n;
        int count=0;
        int i=0;
        while((m>>i)>0)
            {if((m>>i)&1==1)count++;i++;}
        return count;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章