見習村04 - Bit Counting

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

1
2
3
def count_bits(n)
# Program Me
end

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) {
// Program Me
};

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,再將其切開分群,然後進行加總

https://ithelp.ithome.com.tw/upload/images/20200919/20120826nf6v12ujjB.jpg
圖片來源:Unsplash Ben White

Hint & Reference

Solution

Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 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;
};