24
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – PyRulez Mar 17 '15 at 16:11
  • 8
    \$\begingroup\$ @PyRulez Any number is zero modulo 1. \$\endgroup\$ – Thomas Mar 17 '15 at 17:18
  • 1
    \$\begingroup\$ Hi, you have chosen a wrong answer as accepted answer (by default tie breaker logic of earliest post). \$\endgroup\$ – Optimizer Mar 18 '15 at 9:11
  • 4
    \$\begingroup\$ @Thomas I never said it was a helpful tip. \$\endgroup\$ – PyRulez Mar 18 '15 at 15:40
  • 2
    \$\begingroup\$ 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? \$\endgroup\$ – Level River St Mar 18 '15 at 15:53

63 Answers 63

0
\$\begingroup\$

Pari/GP, 13 bytes

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

hammingweight

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Perl 6, 18 bytes

*.base(2).comb.sum

Works with any nonnegative integer, in fact.

Try it online!

\$\endgroup\$
-1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – ATaco Oct 10 '16 at 3:57
  • \$\begingroup\$ Uhm,.. what? You can declare by defining in lua. \$\endgroup\$ – Sempie Oct 12 '16 at 17:59
  • \$\begingroup\$ The declaring of these things must be part of the code. \$\endgroup\$ – ATaco Oct 12 '16 at 22:04
  • \$\begingroup\$ 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 \$\endgroup\$ – ATaco Oct 12 '16 at 22:05

protected by Community Mar 19 '15 at 22:05

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.