Leetcode 191. Number of 1 Bits

文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡書

1. Description

Number of 1 Bits

2. Solution

  • Version 1
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        int m = 1;
        while(n) {
            count += (m & n);
            n >>= 1; 
        }
        return count;
    }
};
  • Version 2
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        int m = 1;
        while(n) {
            count++;
            n &= (n - 1); 
        }
        return count;
    }
};

Reference

  1. https://leetcode.com/problems/number-of-1-bits/description/
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Write a function that takes an unsigned integer and retur...
    NapoleonY閱讀 184評論 0 0
  • Write a function that takes an unsigned integer and retur...
    ShutLove閱讀 184評論 0 0
  • Number of 1 Bits Write a function that takes an unsigned ...
    gammaliu閱讀 269評論 0 0
  • 每一個清晨,頭腦都有點暈暈乎乎。有時候我們自己會非常的沒有方向感,忙忙碌碌卻找不到一絲絲的成就感。 不要去想太多亂...
    鴻鵠小志閱讀 125評論 1 1
  • 梅雪詩句傲戰(zhàn)寒, 行筆執(zhí)畫飛白舞。 論孤可奇幾回人, 現(xiàn)作嬈姿紅一只。 2017年7月10日為我欣賞了網(wǎng)友畫的梅花...
    春城怡景閱讀 365評論 18 21

友情鏈接更多精彩內(nèi)容