# Count the number of ones in an unsigned 16-bit integer

Write some statement(s) which will count the number of ones in an unsigned sixteen-bit integer.

For example, if the input is 1337, then the result is 6 because 1337 as a sixteen bit binary number is 0000010100111001, which contains six ones.

• Tip: just as the some of digits in a number is congruent to the number mod 9, the some of bits equals the number mod 1. – PyRulez Mar 17 '15 at 16:11
• @PyRulez Any number is zero modulo 1. – Thomas Mar 17 '15 at 17:18
• Hi, you have chosen a wrong answer as accepted answer (by default tie breaker logic of earliest post). – Optimizer Mar 18 '15 at 9:11
• @Thomas I never said it was a helpful tip. – PyRulez Mar 18 '15 at 15:40
• Why is this question attracting close votes AFTER most of the answers have been posted? Close voters please indicate your reason in the comments. If it is the acceptance of es1024's (very clever) 4-byte answer which does not comply with standard loopholes (because it uses a builtin) please state that this is the reason. Otherwise, what is it? – Level River St Mar 18 '15 at 15:53

# Pari/GP, 13 bytes

Pari/GP has a built-in for Hamming weight.

hammingweight


Try it online!

# Perl 6, 18 bytes

*.base(2).comb.sum


Works with any nonnegative integer, in fact.

Try it online!

## LUA 55 bytes

while(i>0)do if(v-i)>=0 then c=c+1;v=v-i;end i=i/2 end


v is the value

i is the max value of an (x)bit Integer, 65535 in this example.

c counts one up, if there's a remainder from (i-l), which means that a one is found.

This is more a simple algorithm than a single statement.

• Not valid, c is not declared, and will error when (c=c+1) happens, you cannot assume i is a value, and you cannot assume the input is v. Please use the standard io methods. – ATaco Oct 10 '16 at 3:57
• Uhm,.. what? You can declare by defining in lua. – jawo Oct 12 '16 at 17:59
• The declaring of these things must be part of the code. – ATaco Oct 12 '16 at 22:04
• EG, i=65535 c=0 v = io.read() while(i>0)do if(v-i)>=0 then c=c+1;v=v-i;end i=i/2 end – ATaco Oct 12 '16 at 22:05