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.4

題目很簡單,直接循環與十六進制0X1進行&運算即可,需要注意的是累計加法的時候要添加括號。

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int bitnum=0;
        while(n!=0)
        {
            bitnum=bitnum+(n&0x1); //或者 bitnum+=n&0x1, 如果寫成 bitnum=bitnum+n&0x1 是錯的,這也是唯一需要注意的地方。
            n=n>>1;
        }
        return bitnum;
    }
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章