[LeetCode] Number of 1 Bits

CodingTest|2025. 12. 18. 02:11

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

Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).

 

Example 1:

Input: n = 11

Output: 3

Explanation:

The input binary string 1011 has a total of three set bits.

Example 2:

Input: n = 128

Output: 1

Explanation:

The input binary string 10000000 has a total of one set bit.

Example 3:

Input: n = 2147483645

Output: 30

Explanation:

The input binary string 1111111111111111111111111111101 has a total of thirty set bits.

 

Constraints:

  • 1 <= n <= 2^31 - 1

A prroblem is converting the given number into its binary representation and returning the count of 1 bits.

주어진 숫자를 이진법 표기로 바꾸고, 그 안에 있는 1 비트의 수를 세어 리턴하는 문제.

 

It was a problem that could be solved simply by using bit operators.

You just check whether each bit is 1 starting from the least significant bit,

and shift it step by step using the >> bitwise operator. That’s it.

비트 연산자를 쓰면 간단히 풀 수 있는 문제였다.

맨 끝에서부터 하나씩 비트가 1인지 확인하고 >> 비트 연산자로 옮겨주면서 이동시키면 끝!

class Solution {
    public int hammingWeight(int n) {
        // how can I convert integer to binary string?
        // uses bit operator
        int res = 0;
        while(n != 0){
            if((n & 1) == 1){
                res++;
            }
            n = n >> 1;
        }

        return res;
    }
}

'CodingTest' 카테고리의 다른 글

[LeetCode] Valid Palindrome  (0) 2025.12.15
[LeetCode] 3Sum  (0) 2025.12.04
[LeetCode] Climbing Stairs  (0) 2025.11.26