본문 바로가기
알고리즘/Codewars

[Codewars] Bit Counting (6 kyu) / JavaScript

by fluss 2022. 10. 7.

https://www.codewars.com/kata/526571aae218b8ee490006f4

 

Codewars - Achieve mastery through coding practice and developer mentorship

Coding practice for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case

 

설명:

정수를 입력으로 받고 그 숫자의 이진 표현에서 1과 같은 비트의 수를 반환합니다. 입력은 음수가 아닙니다.

예: 1234의 이진 표현은 10011010010, 그러므로 이 경우 함수는 5를 반환한다.

 

풀이

var countBits = function(n) {
  return n.toString(2).split('').filter(el => el === '1').length;
};

n을 toString(2)로 2진수로 바꾸고 split으로 하나씩 배열에 넣어준다. 그리고 filter로 값이 '1'인 경우만 모아서 새로운 배열을 만들고 그 배열의 길이를 반환한다.

 

다른 사람의 좋았던 풀이

countBits = n => n.toString(2).split('0').join('').length;

2진수로 바꾼 문자열을 '0'을 기준으로 자르고 합친 문자열(1로만 이루어진 문자열이 된다.)의 길이를 반환했다.

댓글