[LeetCode] Number of 1 Bits

준규·2022년 12월 24일

1.문제


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


unsigned integer 가 주어질 때 1 비트의 갯수를 리턴하는 문제이다.


Example 1

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

Example 2

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

Example 3

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

Constraints:

  • The input must be a binary string of length 32.

2.풀이

  1. 주어지는 10진수 n을 2진수로 변환한다.
  2. 변환한 2진수에서 0비트를 모두 없애준다.
  3. 남은 2진수의 길이를 리턴해준다.

/**
 * @param {number} n - a positive integer
 * @return {number}
 */
const hammingWeight = function (n) {
  let binary = n.toString(2); // 2진수로 변환

  binary = binary.replace(/0/g, ""); // 2진수에서 0 비트는 모두 없앤다
  return binary.length; // 1비트로만 남은 binary의 길이가 1비트의 갯수이다
};

3.결과

profile
안녕하세요 :)

0개의 댓글