[ソードフィンガー15]バイナリの1の数

方法1:ビット演算:時間O(1)、空間O(1)

回答:

  1. n&(n-1)ごとにビット演算を使用して、バイナリ位置の1を1回クリアします
    ここに画像の説明を挿入します
class Solution {
    
    
public:
    int hammingWeight(uint32_t n) 
    {
    
    
        // 1.位运算
        int res = 0;
        while (n)
        {
    
    
            res++;
            n = n & (n - 1);
        }
        return  res;   
    }
};

おすすめ

転載: blog.csdn.net/qq_45691748/article/details/112531169