[codewars] Bit Counting

KJA·2022년 8월 31일
0

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


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

문제 해결

var countBits = function(n) {
  let count = 0;
  n.toString(2).split('').forEach(element => {
    if (element === '1') count++;
  });
  return count;
};

다른 풀이

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

0개의 댓글

Powered by GraphCDN, the GraphQL CDN