알고리즘
DaleStudy | Leetcode Study 3주차 - Number of 1 Bits
수쿵IT
2025. 8. 9. 18:19

문제
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
풀이
function hammingWeight(n: number): number {
return n.toString(2).replace(/0/g, '').length;
};
이 문제는, 주어진 인풋의 값을 이진수로 변경했을 때, "1"의 갯수를 찾으면된다. 자바스크립트의 toString 메서드를 이용하면 2진수로 숫자를 변경할 수 있고, 거기에 정규식을 이용해서 "0"을 빼준 뒤 그 길이를 구해주면 끝난다.
Link: https://leetcode.com/problems/number-of-1-bits/description/