iT邦幫忙

第 12 屆 iT 邦幫忙鐵人賽

DAY 4
2
自我挑戰組

見習村-30 Day CodeWars Challenge系列 第 4

見習村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

  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

想法(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

  # 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;
  };

上一篇
見習村03 - Highest Scoring Word
下一篇
見習村05 - The Hashtag Generator
系列文
見習村-30 Day CodeWars Challenge30

尚未有邦友留言

立即登入留言