Don't say so much, just coding...
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
def count_bits(n)
# Program Me
end
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
var countBits = function(n) {
// Program Me
};
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);
想法(1): A system of numerical notation that has 2 rather than 10 as a base.
想法(2): 將傳入的數字轉為 binary,再將其切開分群,然後進行加總
圖片來源:Unsplash Ben White
# 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
// 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;
};