#C,21#
for(n=0;x;n++)x&=x-1;
you said "write some statements" (not "a function") so I've assumed the number is supplied in x
and the number of 1's is returned in n
. If I don't have to initialize n
I can save 3 bytes.
This is an adaptation of the famous expression x&x-1
for testing if something is a power of 2 (false if it is, true if it isn't.)
Here it is in action on the number 1337 from the question. Note that subtracting 1 flips the least significant 1 bit and all zeroes to the right.
0000010100111001 & 0000010100111000 = 0000010100111000
0000010100111000 & 0000010100110111 = 0000010100110000
0000010100110000 & 0000010100101111 = 0000010100100000
0000010100100000 & 0000010100011111 = 0000010100000000
0000010100000000 & 0000010011111111 = 0000010000000000
0000010000000000 & 0000001111111111 = 0000000000000000
EDIT: for completeness, here's the naive algorithm, which is one byte longer (and quite a bit slower.)
for(n=0;x;n/=2)n+=x&1;