본문 바로가기
알고리즘/leetcode

191. Number of 1 Bits

by 유이얼 2022. 7. 24.
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 

'알고리즘 > leetcode' 카테고리의 다른 글

19. Remove Nth Node From End of List  (0) 2022.07.24
190. Reverse Bits  (0) 2022.07.24
231. Power of Two  (0) 2022.07.24
120. Triangle  (0) 2022.07.22
Subsets II - medium  (0) 2021.08.04