문제를 본 날: 2022년 11월 6일 오후 3:30 (GMT+9)

문제를 푼 날: 2022년 11월 6일 오후 3:36 (GMT+9)

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

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

Note:

Example 1:

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string11111111111111111111111111111101 has a total of thirty one '1' bits.

Constraints:

Solution

1. 기본 아이디어

1101 이런 수가 있다고 할 때, n & 1 의 결과는 맨 끝 자리가 1이면 1이 되고, 0이면 0이 된다.

이 점을 이용해서 계산하고, 계산한 후에는 자리를 오른쪽으로 밀어서 모든 자릿수에 대해 1이면 ret 에 더함으로써 답을 도출해낸다.

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