32
\$\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\$
8
  • 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\$ Commented Mar 17, 2015 at 16:11
  • 10
    \$\begingroup\$ @PyRulez Any number is zero modulo 1. \$\endgroup\$
    – Thomas
    Commented Mar 17, 2015 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
    Commented Mar 18, 2015 at 9:11
  • 6
    \$\begingroup\$ @Thomas I never said it was a helpful tip. \$\endgroup\$ Commented Mar 18, 2015 at 15:40
  • 4
    \$\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\$ Commented Mar 18, 2015 at 15:53

79 Answers 79

1
\$\begingroup\$

Clip, 6

2 ways:

cb2nx1

This is a straightforward translation of the requirement: the count of ones in the base-2 representation of number.

r+`b2n

Another method, which takes the sum of the digits of the base-2 representation.

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

Octave, 18

sum(dec2bin(s)-48)

Example:

octave:1> s=1337
s =  1337
octave:2> sum(dec2bin(s)-48)
ans =  6
\$\endgroup\$
1
\$\begingroup\$

GML (Game Maker Language), 21 bytes

for(n=0;x;n/=2)n+=x&1
\$\endgroup\$
1
\$\begingroup\$

><> (Fish), 24 bytes + 2 = 26

0$11.>~n;
2,:?!^:2%:{+}-

The program just does repeated mod 2, subtract and divide until the input number becomes zero, then prints the sum of the mod 2s.

Test with the -v flag, e.g.

py -3 fish.py ones.fish -v 1337
\$\endgroup\$
2
  • \$\begingroup\$ For a 16bit integer the codepoint input probably not adequate. (The -v flag version still works.) \$\endgroup\$
    – randomra
    Commented Mar 17, 2015 at 17:29
  • \$\begingroup\$ @randomra Damn, you're right. While Unicode input does work, 16-bit is just a few orders of magnitude out of range... \$\endgroup\$
    – Sp3000
    Commented Mar 17, 2015 at 20:24
1
\$\begingroup\$

Perl, 21

$r=grep$v&1<<$_,0..15
\$\endgroup\$
1
\$\begingroup\$

PowerShell (51 bytes)

"$([char[]][convert]::ToString($s,2)|%{"+$_"})"|iex

Explanation:
[convert]::ToString($s,2) produces a binary string representation from $s.
[char[]] casts it as a char array and allows us to enumerate each char.
|%{"+$_"} prepends each character with a + sign
"$()" implicitly calls .ToString() on the resulting sub expression
|iex sums the piped string (ie. "+1 +0 +1 +1 +0 +1 +0 +0" = 4)

\$\endgroup\$
1
  • \$\begingroup\$ Hiya! Following the same logic you have, why not use the inline -join operator and an implicit .ToString() to achieve 45 bytes with [char[]][convert]::ToString($s,2)-join'+'|iex ... OR, as a different approach use inline -replace operator to achieve 43 bytes with ([convert]::ToString($s,2)-replace0).length \$\endgroup\$ Commented Jan 7, 2016 at 21:08
1
\$\begingroup\$

Clojure, 42 bytes

#(count(filter #{\1}(Long/toString % 2)))

Reading right to left, convert to a binary string, convert to a sequence of characters, filter on 1s and count how many you have.

EDITED With help from Sieg

\$\endgroup\$
7
  • \$\begingroup\$ 42: #(count(filter #{\1}(Integer/toString% 2))) \$\endgroup\$
    – seequ
    Commented Mar 18, 2015 at 15:55
  • \$\begingroup\$ You need one more character #(count(filter #{\1}(Integer/toString % 2))) \$\endgroup\$ Commented Mar 18, 2015 at 15:58
  • \$\begingroup\$ No you don't. :) \$\endgroup\$
    – seequ
    Commented Mar 18, 2015 at 15:59
  • \$\begingroup\$ This is what I got when I tried it: CompilerException java.lang.IllegalArgumentException: No matching method: toString_PERCENT_ \$\endgroup\$ Commented Mar 18, 2015 at 16:02
  • \$\begingroup\$ I tested it in Try Clojure. Apparently the page suddenly doesn't recognize Integer/toString. It worked a second ago though. \$\endgroup\$
    – seequ
    Commented Mar 18, 2015 at 16:04
1
\$\begingroup\$

Haskell 42 chars

t 0=[]
t n=t(quot n 2)++[rem n 2]
f=sum.t

declares the function f :: Integer -> Integer
use from the interactive interpreter as f <number> or add the line main=print$f <number> to the end of the file.

\$\endgroup\$
1
  • \$\begingroup\$ You can save a lot of bytes by directly summing the rem n 2s instead of building a list of it and by using div instead of quot: t 0=0 t n=t(div n 2)+rem n 2 - no f anymore. \$\endgroup\$
    – nimi
    Commented Mar 22, 2015 at 18:13
1
\$\begingroup\$

Matlab, 13 bytes

de2bi creates a vector of zeros and ones representing the binary number, and sum just returns the sum of all the entries.

sum(de2bi(n))
\$\endgroup\$
1
\$\begingroup\$

K5, 9 bytes

+/(16#2)\

I used k5's "unpack" overload for \ to split the number into base 2 digits. You can try it online here using oK.

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

𝔼𝕊𝕄𝕚𝕟, 4 chars / 11 bytes (non-competitive)

⨭⟦ïⓑ

Try it here (Firefox only).

Explanation

Converts input to binary, splits along chars, and gets sum of resulting array.

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

Pyt, 1 byte

Hooray for built-ins.

Ħ

Try it online!

Non-built-in:

Pyt, 3 bytes

ɓƖŚ

Try it online!

Explanation:

      Implicit input
ɓ     Convert to binary string
Ɩ     Cast as integer
Ś     Sum of digits
      Implicit output
\$\endgroup\$
0
1
\$\begingroup\$

Brachylog, 2 bytes

ḃ+

Try it online!

Just about exactly the Jelly answer.

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

><>, 18 bytes

0$:2%:{+}-2,:@?!n!

Try it online!

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

MathGolf, 2 bytes

âΣ

Try it online!

Explanation

â    convert to binary
 Σ   sum(list), digit sum(int)
\$\endgroup\$
8
  • \$\begingroup\$ Completely unrelated to this answer of yours, but I'm unable to find the MathGolf chat anymore.. Is there an infinite loop or infinite list in MathGolf? \$\endgroup\$ Commented Mar 5, 2019 at 15:04
  • \$\begingroup\$ I've been stressed out with school and work for the past few months, so the chat must be inactive. There's no implicit infinite loop, but if you can make sure that the top of the stack evaluates to true you could use the do-while-without-pop. Once I feel that I have time to answer questions on a regular basis, I'll ask to have the chat reopened. Right now I'm just building a todo-list of features I want to add. \$\endgroup\$
    – maxb
    Commented Mar 5, 2019 at 15:11
  • \$\begingroup\$ I'm getting "Not yet implemented" ValueErrors for all while / do-while loops.. :S Unless I'm doing something wrong.. \$\endgroup\$ Commented Mar 5, 2019 at 15:28
  • \$\begingroup\$ you should use them like {1}∟ or using the fixed size blocks. It's on my todo-list to have the loop operators also close the block, but it's not implemented as of now. \$\endgroup\$
    – maxb
    Commented Mar 5, 2019 at 16:08
  • 1
    \$\begingroup\$ @KevinCruijssen Maybe I need to clarify the loop structure a bit better, but the correct implementation would be something like {îo}▲. Your script first does Ä1∟ which will push 1 onto the stack until the memory is full or TIO timeouts, then it would print the length of the loop. Basically, in pseudo code it would be int i = 0; do {i++; stack.push(1);} while (i != 0); print(i). The code would never reach the last part since the loop is infinite. Basically, loops are constructed as {<loop code>}<loop operator> \$\endgroup\$
    – maxb
    Commented Mar 6, 2019 at 13:27
1
\$\begingroup\$

K (ngn/k), 4 bytes

+/2\

Try it online!

Convert to base 2, sum up.

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

C# 38 bytes

Convert.ToString(X,2).Count(C=>C==49);
\$\endgroup\$
1
  • \$\begingroup\$ @Vincent McNabb has suggested a golf which saves one byte (replacing '1' with 49) \$\endgroup\$
    – rydwolf
    Commented Apr 8, 2021 at 5:06
1
\$\begingroup\$

JavaScript, 19 bytes

f=n=>n&&n%2+f(n>>1)

Try it online!

Nice and simple

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

Desmos, 40 38 bytes

f(x)=floor(mod(x/2^{[0...x]},2)).total

Try it on Desmos!

-2 bytes thanks to emanresu A

\$\endgroup\$
2
  • \$\begingroup\$ Not sure how to golf this but something like desmos.com/calculator/chncunsuhu might be shorter? \$\endgroup\$
    – emanresu A
    Commented May 6, 2022 at 4:02
  • \$\begingroup\$ @emanresuA thanks that's one byte less and two bytes less with dot notation for total \$\endgroup\$
    – naffetS
    Commented May 6, 2022 at 4:05
0
\$\begingroup\$

Go, 24

This is an adaptation of the C solution by @steveverrill

n:=0;for;x>0;n++{x&=x-1}

We need to explicitly declare n outside the loop to keep it in scope.

Go requires curly braces as well, and the check in the for loop must be a boolean expression.

http://play.golang.org/p/Z_iuGL5nZ5

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

WDC 65816, 8 bytes

Assuming 8-bit XY (P.x = 1), the following 8 bytes of object code produce the popcnt of A in X within 145 cycles:

A2 00 4A 90 01 E8 D0 FA

This works on a 65816 whether A is 8-bit (P.m = 1) or 16-bit (P.m = 0), and it has also been tested in a virtual 6502 with 8-bit values. With 16-bit XY on a 65816 (P.x = 0), one more byte is needed: replace A2 00 with A2 00 00.

Assembly source:

  ldx #0       ; A2 00, or A2 00 00 in 16-bit XY mode
loop:
  lsr a        ; 4A    Copy bit 0 of A to carry and shift A right by 1
  bcc zerobit  ; 90 01 If carry is 1, add 1 to X
  inx          ; E8
zerobit:
  bne loop     ; D0 FA If the last ALU result was nonzero, keep counting

The bne instruction branches on the zero flag, which changes whenever an instruction writes to register A, X, or Y. For a 1 bit, inx is the last instruction to write to A, X, or Y, and X is nonzero if there are 1 to 255 bits (only 16 are possible!), so the loop continues. For a 0 bit, lsr a is the last instruction to write to A, X, or Y, and A is nonzero only if there are more bits to count.

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

perl (35 characters)

$b=sprintf("%b",$d);$c=()=$b=~/1/g;
\$\endgroup\$
0
\$\begingroup\$

Bash, 63 51 47 bytes

[ $1 = 0 ]&&echo 0||echo $[$1%2+`$0 $[$1/2]`]

The shorter the code, the clearer the meaning :).


51:

[ $1 -ne 0 ]&&echo $[($1&1)+$($0 $[$1/2])]||echo 0

Recursive script instead of script with recursing function.


The "negative-cond || instruction" idiom instead of boring "if cond; then instruction; fi " is our friend here.

Note that echo should return 0 (true), so [ $1 -ne 0 ] && echo $[$[$1&1]+$(n $[$1/2])]

has the logical value of [ $1 -ne 0 ] alone.

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

Perl 6: 17

The first thing that comes to mind is

[+] 1337.base(2).comb; # returns 6

Although this doesn't have any arbitrary limits ( the only limits are how much memory you have, and how long you are willing to wait )

[+] ( uint64.Range.max * 2 + 1 ).base(2).comb; # returns 65

# 340282366920938463463374607431768211455
my $uint128-max = :2( 1 x 128 );
[+] $uint128-max.base(2).comb; # returns 128

my $uint8192-max = :2( 1 x 8192 ); # 2467 digit Int
[+] $uint8192-max.base(2).comb; # returns 8192 (takes about a second currently)

Without making it into a Callable the shortest way to write this is to put the Int into the "default" variable $_. ( .method is always short for $_.method )

$_ = 1337;
[+] .base(2).comb;
given 1337 { # Perl6's with/switch statement
  [+] .base(2).comb
}
[+] .base(2).comb given 1337; # ditto
if 1337 -> $_ { # pointy block
  [+] .base(2).comb
}

If you want to create a Callable you could just put it into a Block.

my $code-ref = {[+] .base(2).comb};
# if it is called with an argument it places it in $_
# if called without an argument uses the $_ from an outer scope

If you really want to call it as a normal subroutine:

my &f={[+] .base(2).comb}; # sub f($_){[+] .base(2).comb}

say f 1337; # 6

$_ = 1337;
say f; # 6

Based on your requirements I'd guess that the answer you are looking for is:

[+] .base(2).comb

This assumes that the value is already in $_. It would most likely be the last statement in a subroutine, the right side of an assignment, or an argument to a subroutine or method. ( Otherwise it calculates the result only to throw it away, unless the compiler notices that the result is unused )


In case you were wondering [+] 1, 2, 3 can be considered short for (1,2,3).reduce(&[+]).
Where &[+] is short for &infix:< + > the collection of multi subs available in the current scope that are responsible for the numerical infix addition operator +.

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

O, 7 bytes

H2b~]+o

Explanation:

H        Push input into array
  2b~    Push all the bits of the binary form to the array
     ]+o Add them all up and output the array
\$\endgroup\$
0
\$\begingroup\$

Clip, 22 chars (25 for full program, or 27 for working with zero)

[Fy?!%lyWOO])Fmy#WilyW

Prefix this with F<some value> to get the answer for that value. Or, for a full program to read from stdin, prefix the code with Fnx. In a previous answer, I golfed a way in Clip to check if something's a power of two. I always return one in that case. Otherwise, increment the result of applying this function (recursively) to 2^(floor(log2(<function parameter>))).

To make this work with zero (returning 0), use (28 chars):

[Fy?!yZ]?!%lyWOO])Fmy#WilyW
\$\endgroup\$
0
\$\begingroup\$

TeaScript, 9 bytes (non-competitive)

x÷f»l¦1)n

Try it here.

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

Seriously, 6 bytes (non-competitive)

This one is fun and neat, and given the number of non-competitive entries it has attracted, I might as well add a Seriously answer.

'12,¡c

Try it online

Explanation:

'12,¡c
   ,     get input
  2 ¡    convert to binary string
'1   c   count the occurrences of "1"
         (implicit print at EOF)
\$\endgroup\$
0
\$\begingroup\$

Candy, 15 bytes

I would have thought this would do a bit better, but the lack of an operator to convert numbers to a base 2 string seems to have hurt it. Maybe in a future version of Candy to pull an int from the stack and push 1's and 0's. That would make this one kind of boring, just XS?.

(~A2%h2/LD{)|=Z

The long form is:

while   # stack not empty
  peekA
  pushA    
  digit2
  mod       # get low bit
  popAddZ   # Z = Z + low bit
  digit2
  div
  floor     # integer div 2
  dupl
  if        # if the top of stack is non-zero
endwhile    # NOTE that the endwhile is in an if-then clause
  else
    popA
    pushZ   # NOTE the lack of an endif.
            #  braces and parens are calculated as the
            #  program counter advances over them
\$\endgroup\$
0
\$\begingroup\$

C# 45

int o=Convert.ToString(n,2).Count(x=>x=='1');

where o holds the amount of ones and where n is the number.

Alternative and faster C# 6.0 88 bytes

int o=b(n,16).Count(x=>x=='1');
static string b(int v,int l)=>(l>1?b(v>>1,l-1):null)+"01"[v&1];

where the o holds the number of ones and where the n is the number.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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