countBits.js

Codewars 알고리즘 풀이


Problem

  • Write a function that takes an integers as input, and returns the number of bits that are equal to one in the binary representation of that number.
    • 해당 숫자의 2진법(Binary representation)에서 1의 비트 수를 반환한다.
  • You can guarantee that input is non-negative.
    • 입력은 양수만 포함한다.



Solution 01

function countBits(n) {
  return n.toString(2).split('0').join('').length;
}

countBits(0);   // 0 (0)
countBits(1);   // 1 (1)
countBits(2);   // 1 (10)
countBits(3);   // 2 (11)
countBits(4);   // 1 (100)
countBits(5);   // 2 (101)
countBits(6);   // 2 (110)
countBits(7);   // 3 (111)
countBits(8);   // 1 (1000)
countBits(9);   // 2 (1001)
countBits(10);  // 2 (1010)


Solution 02

function countBits(n) {
  return n.toString(2).replace(/0/g, '').length;
}

countBits(0);   // 0 (0)
countBits(1);   // 1 (1)
countBits(2);   // 1 (10)
countBits(3);   // 2 (11)
countBits(4);   // 1 (100)
countBits(5);   // 2 (101)
countBits(6);   // 2 (110)
countBits(7);   // 3 (111)
countBits(8);   // 1 (1000)
countBits(9);   // 2 (1001)
countBits(10);  // 2 (1010)


Solution 03

function countBits(n) {
  let count = 0;
  
  while (n > 0) {
    if (n % 2 === 0) {
      count++;
    }
    
    n = Math.floor(n / 2);
  }
  return count;
}

countBits(0);   // 0 (0)
countBits(1);   // 1 (1)
countBits(2);   // 1 (10)
countBits(3);   // 2 (11)
countBits(4);   // 1 (100)
countBits(5);   // 2 (101)
countBits(6);   // 2 (110)
countBits(7);   // 3 (111)
countBits(8);   // 1 (1000)
countBits(9);   // 2 (1001)
countBits(10);  // 2 (1010)