알고리즘/leetcode

191. Number of 1 Bits

유이얼 2022. 7. 24. 01:11
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int ans = 0;
        while (n) {
            n &= n - 1;
            ++ans;
        }
        return ans;
    }
};

n & n - 1 : remove the last '1' bit 

저작자표시 비영리 (새창열림)