-
[Codewars] Bit CountingAlgorithm 2021. 3. 29. 19:21
www.codewars.com/kata/526571aae218b8ee490006f4/train/javascript
Codewars: Achieve mastery through challenge
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
www.codewars.com
더보기자연수 n이 주어졌을 때, n을 2진수로 바꾼 뒤, 1의 개수를 구하는 문제이다.
문제
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
풀이
- 임의의 수n을 2진수로 바꿔줌(toString).
- 그 값을 배열로 나눠서 1이 몇 개 들어있는지 확인 후에 카운트 리턴
var countBits = function(n) { var bit = n.toString(2); var bitArr = bit.split(''); var count = 0; for(var i = 0; i < bitArr.length; i++) { if(bitArr[i] === '1') count++; } return count; };
'Algorithm' 카테고리의 다른 글
[Codewars] Stop gninnipS My sdroW! (0) 2021.04.01 [프로그래머스] 기능개발 (0) 2021.03.30 [Codewars] RGB To Hex Conversion (0) 2021.03.23 [Codewars] Dubstep (0) 2021.03.22 [Codewars] Array.diff (0) 2021.03.20