Skip to content

Latest commit

 

History

History
27 lines (19 loc) · 774 Bytes

bit-counting.md

File metadata and controls

27 lines (19 loc) · 774 Bytes

Bit Counting 6 Kyu

LINK TO THE KATA - BITS ALGORITHMS

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

Solution

const getBinary = num => {
  return num.toString(2)
}

const countBits = num => {
  const binaryNumber = getBinary(num)

  return binaryNumber.split('').reduce((acc, cur) => acc + Number(cur), 0)
}