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
Sample Testing 1 2 3 4 5 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 1 2 3 var countBits = function (n ) { };
Sample Testing 1 2 3 4 5 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 想法(1): A system of numerical notation that has 2 rather than 10 as a base. 想法(2): 將傳入的數字轉為 binary,再將其切開分群,然後進行加總
圖片來源:Unsplash Ben White
Hint & Reference
Solution Ruby 1 2 3 4 5 6 7 8 9 10 11 12 13 14 def count_bits (n) n.to_s(2 ).count('1' )end def count_bits (n) n.to_s(2 ).chars.map{ |x| x.to_i }.reduce{ |sum, x| x += sum }end def count_bits (n) n.to_s(2 ).chars.map(&:to_i ).inject(&:+ )end
Javascript 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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 };var countBits = function (n ) { return n.toString(2 ).split('0' ).join('' ).length; };