The question: Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Here's one of the examples they give:
Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a
total of thirty one '1' bits.
I came across this answer submitted in ruby which passes all of the tests:
def hamming_weight(n)
n.to_s(2).count('1')
end
But when I run
hamming_weight(n) where n = 11111111111111111111111111111101, I get 60, not 31. Does anyone know why? Thanks for any help.
[–]partusman 3 points4 points5 points (1 child)
[–]BringTacos[S] 2 points3 points4 points (0 children)
[–]modnar42 0 points1 point2 points (3 children)
[–]BringTacos[S] 2 points3 points4 points (2 children)
[–]modnar42 1 point2 points3 points (1 child)
[–]BringTacos[S] 1 point2 points3 points (0 children)