LeetCode 191 Number of 1 Bits

Tag: 位操作 LeetCode Posted on 2022-02-22 21:00:07 Edited on 2022-02-22 21:00:07 Views: 133

概述

https://leetcode.com/problems/number-of-1-bits/

解法

利用 n & (n - 1) 删除 n 中的最后一个 1:

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        while (n != 0) {
            n = n & (n - 1);
            count ++;
        }
        return count;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/