NumberOf1Bits

Published at 2021-11-20

class Solution:
    def hammingWeight(self, n: int) -> int:
        ans = 0
        while n:
            n &= (n-1)
            ans += 1
        return ans

    # c++로도 함
/**
 * @param {number} n - a positive integer
 * @return {number}
 */
var hammingWeight = function(n) {
    let cnt = 0;
    while (n){
        n &= (n-1);
        cnt ++;
    }
    return cnt
};
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;

        while (n) {
            // printf("전 %u \n", n);
            n &= (n - 1);
            // printf("후 %u \n", n);
            count++;
        }

        return count;
    }
};


// 이진수에서 1씩 빼서 and 연산을 하면 뒤에있는 1부터 하나씩 사라지게됨(ㅈㄴ신기;;)
// 예를들어 1011이 있다. 거기서 1을 빼면 1010이잖아? 이걸 &연산하면 1010임.
// 그 담에 또 1010에서 1을 빼. 그럼 1001이겠지? 두개 &연산하면 1000이 됨.
// 또 그담에 1000에서 1을 빼면 0111이잖? &연산-> 0000됨. n이 전부 0이니까 false취급되서 반복문탈출
// 총 횟수 3번이잖? 그럼 3리턴하고 끝;;;; 와 개천재다