CodeWar Weekly - 0224~0301

CodeWar Weekly[0224-0301]

6kyu Bit Counting

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

解題思考:先需要思考如何轉 2 進位,會用到 to_s(2),再來就有幾種方式跟其方法了
ex: count、chars、map、reduce、inject …

參考方法 & 學習筆記

Ruby

count

難得基本上都沒有查的一次~
不過後來才想到才有 count,所以還是記錄一下好惹…(雖然沒什麼好紀錄的

Returns the number of elements. If an argument is given, counts the number of elements which equals to obj. If a block is given, counts the number of elements yielding a true value.

1
2
3
4
ary = [1, 2, 4, 2]
ary.count #=> 4
ary.count(2) #=> 2
ary.count{ |x| x % 2 == 0 } #=> 3

JavaScript

Object.prototype.toString()

The toString() method returns a string representing the object.

1
2
3
4
5
6
7
8
9
10
11
12
function Dog(name) {
this.name = name;
}

const dog1 = new Dog('Gabby');

Dog.prototype.toString = function dogToString() {
return '' + this.name;
}

console.log(dog1.toString());
// expected output: "Gabby"

(下方是雷~~~!!!)


Ruby

Solution(1):

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

Solution(2):

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

Solution(3):

1
2
3
def count_bits(n)
n.to_s(2).count('1')
end

JavaScript

Solution(1):

1
return n.toString(2).split('0').join('').length;

Solution(2):

1
return n.toString(2).replace(/0/g,'').length;

參考資料

查惹一下正規表示法qq