The Hamming Weight
MediumAcc. 92.4%
+25 XP 10
Counting the Charge
In bitwise computation, the Hamming weight is the count of symbols that are different from zero. For integers, this is the count of 1s in their binary form.
The Assignment
Your function receives a parameter num.
- Initialize
countto 0. - Use a
whileloop as long asnumis greater than 0. - In each step:
- Check if the number is odd (
num % 2 !== 0). If yes, incrementcount. - Update
numby dividing by 2 and rounding down.
- Check if the number is odd (
- Print the final
count.
01EXAMPLE 1
Input
num = 7Output
3Explanation: 7 is 111 in binary (three 1s).
Constraints
- Manual bit-counting loop.
- Do not use toString(2) or bitwise operators.
MathLoopsBinary
JavaScriptSystem handles I/O — write your function only
Loading...
3 Hidden
Input Arguments
num7
Expected Output
3
Click RUN to test your solution