[LeetCode] Number of 1 Bits 位1的個數


 

 

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.

 

很簡單的一道位操作Bit Manipulation的題,最近新出的三道題都沒有啥難度啊,這樣會誤導新人的,做了這三道得出個LeetCode沒啥難度的結論,其實里面好題真的不少,難題也很多,經典題也多,反正就是贊贊贊,32個贊。

 

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int res = 0;
        for (int i = 0; i < 32; ++i) {
            res += (n & 1);
            n = n >> 1;
        }
        return res;
    }
};

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM