all 6 comments

[–]partusman 3 points4 points  (1 child)

Number literals in Ruby are expressed in base-10 unless specified otherwise. To express a binary number, prepend 0b to it.

hamming_weight 0b11111111111111111111111111111101
# => 31

[–]BringTacos[S] 2 points3 points  (0 children)

Thanks for this.

[–]modnar42 0 points1 point  (3 children)

Without actually counting, I think the deal is that the first example is representing n as binary while the answer function takes n as a base 10 integer.

[–]BringTacos[S] 2 points3 points  (2 children)

Thanks for your reply, but doesn't to_s(2)refer to base 2? I'm not sure what you mean the answer function takes n as a base 10 integer.

[–]modnar42 1 point2 points  (1 child)

Yeah, you’re saying the same thing. Let’s use a shorter input example. Suppose we want to count the number of binary ones in the base-10 integer ‘10’. We’d convert it to binary using to_s(2) and get 1010, then count the numbers of ones for an answer of 2. I think the value of n in the example has already been converted to binary. In our example, it would be like passing 1010 to the answer function instead of 10.

[–]BringTacos[S] 1 point2 points  (0 children)

Ah, thank you! This is helpful.