DAY 4
2

04 - Bit Counting

Don't say so much, just coding...

Instruction

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

Ruby

Init

``````  def count_bits(n)
# Program Me
end
``````

Sample Testing

``````  Test.assert_equals count_bits(0), 0
Test.assert_equals count_bits(4), 1
Test.assert_equals count_bits(7), 3
Test.assert_equals count_bits(9), 2
Test.assert_equals count_bits(10), 2
``````

Javascript

Init

``````  var countBits = function(n) {
// Program Me
};
``````

Sample Testing

``````  Test.assertEquals(countBits(0), 0);
Test.assertEquals(countBits(4), 1);
Test.assertEquals(countBits(7), 3);
Test.assertEquals(countBits(9), 2);
Test.assertEquals(countBits(10), 2);
``````

Thinking

• Ruby
• JavaScript

Solution

Ruby

``````  # Solution 1
def count_bits(n)
n.to_s(2).count('1')
end

# Solution 2
def count_bits(n)
n.to_s(2).chars.map{ |x| x.to_i }.reduce{ |sum, x| x += sum }
end

# Solution 3
def count_bits(n)
n.to_s(2).chars.map(&:to_i).inject(&:+)
end
``````

Javascript

``````  // Solution 1
var countBits = function(n) {
let count = 0
let to_binary = n.toString(2)

for(i = 0; i < to_binary.length; i++){
if( parseInt(to_binary.split('')[i]) === 1) {
count += 1
}
}

return count
};

// Solution 2
var countBits = function(n) {
return n.toString(2).split('0').join('').length;
};
``````