15
\$\begingroup\$

Description

Given a number, print the amount of 1s it has in binary representation.

Input

A number >= 0 in base 10 that won't exceed the highest number your language is able to handle.

Output

The amount of 1s in binary representation.

Winning condition

The shortest code wins.

Disallowed

  • Bitwise operators. Other operators, like addition and multiplication, are allowed.
  • Built-in base conversion functions.

Examples

Input:     Ouput:

56432      8


Input:     Output:

45781254   11


Input:     Output:

0          0
\$\endgroup\$
2
  • \$\begingroup\$ Are functions allowed? I want to make a Java solution, but writing full code is too tedious... :/ \$\endgroup\$
    – hyperneutrino
    Commented Feb 13, 2016 at 2:40
  • 1
    \$\begingroup\$ I guess I won't be using Wise for this challenge... :) \$\endgroup\$ Commented Mar 31, 2017 at 17:17

50 Answers 50

17
\$\begingroup\$

APL, 9 12 characters

+/2|⌊⎕÷2*⍳32

This assumes that the interpreter uses 32-bit integers, and that ⎕IO is set to 0 (meaning that monadic begins with 0, rather than 1). I used the 32-bit version of Dyalog APL.

Explanation, from right to left:

  • ⍳32 generates a vector of the first 32 integers (as explained before, because ⎕IO is 0, this vector begins with 0).
  • * is the power function. In this case, it generates 2 to the power of each element of the vector supplied as its right argument.
  • ÷ is the divided-by function. It gives us (evaluated user input) divided by each element of the vector to its right (each power of two).
  • floors each element of the argument to its right.
  • 2| gives us the remainder of each element of to its right divided by 2.
  • / reduces (folds) its right argument using the function to its left, +.

Not quite 9 characters anymore. :(

Old, rule-breaking version:

+/⎕⊤⍨32/2

Explanation, from right to left:

  • 32/2: Replicate 2, 32 times.
  • commutes the dyadic function to its left, which in this case is (i.e., X⊤⍨Y is equivalent to Y⊤X).
  • is the encode function. It encodes the integer to its right in the base given to its left. Note that, because of the commute operator, the right and left arguments are switched. The base is repeated for the number of digits required, hence 32/2.
  • is a niladic function that accepts user input and evaluates it.
  • +/ reduces (folds) its right argument using +. (We add up the 0's and 1's.)
\$\endgroup\$
4
  • 2
    \$\begingroup\$ Doesn't this break the Built-in base conversion functions contraint? \$\endgroup\$
    – Gareth
    Commented Dec 30, 2011 at 21:18
  • \$\begingroup\$ Whoops! Missed that one. \$\endgroup\$ Commented Dec 30, 2011 at 21:19
  • \$\begingroup\$ Gah! Thought I'd given myself a fighting chance with my J program! :-) Nice job. \$\endgroup\$
    – Gareth
    Commented Dec 30, 2011 at 23:01
  • \$\begingroup\$ @Gareth: I didn't realize until reading your explanation just now, but my answer is pretty much identical to yours! I guess that could be expected from APL and J. :) \$\endgroup\$ Commented Dec 31, 2011 at 0:42
11
\$\begingroup\$

Brainbool, 2

,.

The most reasonable interpretation, in my opinion (and what most of the answers use) of "highest number your language is able to handle" is "largest number your language natively supports". Brainbool is a brainfuck derivative that uses bits rather than bytes, and takes input and output in binary (0 and 1 characters) rather than character codes. The largest natively supported number is therefore 1, and the smallest is 0, which have Hamming weights 1 and 0 respectively.

Brainbool was created in 2010, according to Esolang.

\$\endgroup\$
2
  • 11
    \$\begingroup\$ I knew it must have existed, but it took me an hour of sorting through Brainfuck derivatives on Esolang to find Brainbool. \$\endgroup\$
    – lirtosiast
    Commented Jul 8, 2015 at 2:17
  • 2
    \$\begingroup\$ Wow, this post was before the loophole was created! \$\endgroup\$
    – Joao-3
    Commented Mar 14, 2022 at 14:30
8
\$\begingroup\$

Brainfuck, 53 characters

This was missing an obligatory Brainfuck solution, so I made this one:

[[->+<[->->>>+<<]>[->>>>+<<]<<<]>>>>[-<<<<+>>>>]<<<<]

Takes number from cell 1 and puts the result into cell 6.

Unenrolled and commented version:

[  while n != 0
  [  div 2 loop
    -
    >+<  marker for if/else
    [->->>>+<<]  if n != 0 inc n/2
    >
    [->>>>+<<]  else inc m
    <<<
  ]
  >>>>  move n/2 back to n
  [-<<<<+>>>>]
  <<<<
]
\$\endgroup\$
7
\$\begingroup\$

J, 13 characters

(+ the number of digits in the number)

+/2|<.n%2^i.32

Usage: replace the n in the program with the number to be tested.

Examples:

+/2|<.56432%2^i.32
8
+/2|<.45781254%2^i.32
11
+/2|<.0%2^i.32
0

There's probably a way of rearranging this so the number can be placed at the beginning or end, but this is my first J entry and my head's hurting slightly now.

Explanation(mainly so that I understand it in the future)

i.32 - creates an array of the numbers 1 to 32

2^ - turns the list into the powers of two 1 to 4294967296

n% - divides the input number by each element in the list

<. - rounds all the divison results down to the next integer

2| - same as %2 in most languages - returns 0 if even and 1 if odd

+/ - totals the items in the list (which are now just 1s or 0s)

\$\endgroup\$
8
  • \$\begingroup\$ I'll be happy to upvote this once it reads from stdin (or whatever equivalent J has). \$\endgroup\$ Commented Dec 30, 2011 at 18:51
  • \$\begingroup\$ The best I could do I think (maybe, depending on figuring out how) is move the input to the end of the program. Standard input isn't mentioned in the question though? \$\endgroup\$
    – Gareth
    Commented Dec 30, 2011 at 21:18
  • \$\begingroup\$ I'm sorry for not specifying the way of input. It would be unfair to change the rules now, so I'll accept this one. I will mention it next time! \$\endgroup\$
    – pimvdb
    Commented Dec 30, 2011 at 22:21
  • \$\begingroup\$ @pimvdb No problem, it wasn't a complaint. I think with J programs though all you can do is define a verb that operates on the input given it. Not sure how I'd rearrange this to do that though. Maybe JB or one of the other J experts could help me out with that... \$\endgroup\$
    – Gareth
    Commented Dec 30, 2011 at 22:59
  • \$\begingroup\$ ...and having read some more I now see that I was completely wrong about standard input. \$\endgroup\$
    – Gareth
    Commented Dec 31, 2011 at 10:02
6
\$\begingroup\$

Python 2.6, 41 characters

t,n=0,input()
while n:t+=n%2;n/=2
print t

note: My other answer uses lambda and recursion and this one uses a while loop. I think they are different enough to warrant two answers.

\$\endgroup\$
6
\$\begingroup\$

Ruby, 38 characters

f=->u{u<1?0:u%2+f[u/2]}
p f[gets.to_i]

Another solution using ruby and the same recursive approach as Steven.

\$\endgroup\$
5
\$\begingroup\$

GolfScript, 17 16 characters

~{.2%\2/.}do]0-,

Edit: new version saves 1 character by using list operation instead of fold (original version was ~{.2%\2/.}do]{+}*, direct count version: ~0\{.2%@+\2/.}do;).

\$\endgroup\$
5
\$\begingroup\$

C, 45

f(n,c){for(c=0;n;n/=2)c+=n%2;printf("%d",c);}

Nothing really special here for golfing in C: implicit return type, implicit integer type for parameters.

\$\endgroup\$
4
\$\begingroup\$

Python 2.6, 45 characters

b=lambda n:n and n%2+b(n/2) 
print b(input())
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Can be shortened by two characters by using def instead of a lambda. \$\endgroup\$ Commented Dec 31, 2011 at 11:51
  • 1
    \$\begingroup\$ @KonradRudolph: Actually, you lose the advantage once you include the return statement. \$\endgroup\$ Commented Dec 31, 2011 at 18:02
  • \$\begingroup\$ Oops, I forgot that. Stupid. \$\endgroup\$ Commented Dec 31, 2011 at 18:06
  • \$\begingroup\$ You don't need the print b(input()). It is acceptable to return the value and take "input" as arguments for functions. \$\endgroup\$ Commented Mar 31, 2017 at 14:27
4
\$\begingroup\$

Perl, 45 43 36 Characters

$n=<>;while($n){$_+=$n%2;$n/=2}print

Thanks to Howard for 45->43, and to User606723 for 43->36.

\$\endgroup\$
3
  • \$\begingroup\$ You might use $n=int($n/2) which 2 characters shorter. \$\endgroup\$
    – Howard
    Commented Dec 30, 2011 at 16:28
  • \$\begingroup\$ Are we sure we need the int()? $n=<>;while($n){$_+=$n%2;$n/=2}print This will keep looping until $n/2 finally gets close enough to 0, but do we care? ;) \$\endgroup\$
    – user606723
    Commented Dec 30, 2011 at 19:17
  • \$\begingroup\$ @user606723 I just tried that out and it seems to work perfectly, at least for every case up to 1000. \$\endgroup\$
    – PhiNotPi
    Commented Dec 30, 2011 at 20:38
3
\$\begingroup\$

Perl, 30 chars

$==<>;1while$_+=$=%2,$=/=2;say

Based on PhiNotPi's solution, with some extra golfing. Run with perl -M5.010 to enable the Perl 5.10 say feature.

\$\endgroup\$
4
  • \$\begingroup\$ Does the $= special variable do anything special in your program, or is it just another ordinary variable? \$\endgroup\$
    – PhiNotPi
    Commented Dec 30, 2011 at 20:47
  • 2
    \$\begingroup\$ @PhiNotPi: $= only takes integer values, so using it saves me an int. \$\endgroup\$ Commented Dec 30, 2011 at 21:11
  • \$\begingroup\$ Shouldn't the command-line arg be part of the char count? \$\endgroup\$ Commented May 3, 2013 at 10:35
  • \$\begingroup\$ @SohamChowdhury: Not per this meta thread. \$\endgroup\$ Commented May 3, 2013 at 13:59
3
\$\begingroup\$

Common Lisp, 12 chars

(assuming a 1 char variable name - i.e.: 11 + number length)

It's not a base conversion function, so it should work:

(logcount x)

Examples:

[1]> (logcount 0)
0
[2]> (logcount 1)
1
[3]> (logcount 1024)
1
[4]> (logcount 1023)
10
[5]> (logcount 1234567890123456789012345678901234567890)
68

(Using GNU CLISP.)

\$\endgroup\$
1
  • \$\begingroup\$ Hm well, not exactly what I had in mind to see as an answer :) I don't think I can accept this. It's basically just another case of this. \$\endgroup\$
    – pimvdb
    Commented Dec 31, 2011 at 12:31
3
\$\begingroup\$

C, 61 60 57 53 characters

void f(x){int i=0;for(;x;x/=2)i+=x%2;printf("%u",i);}

The function body only is 38 characters. Edit: removed bitwise operator Edit: put printf out of the loop as suggested in the comments Edit: switch to K&R declaration; also, this is no longer C99-specific

\$\endgroup\$
7
  • \$\begingroup\$ I see bitwise!!! \$\endgroup\$
    – Joanis
    Commented Dec 31, 2011 at 6:51
  • \$\begingroup\$ I'm sorry but the AND operator also counts as a bitwise operator. \$\endgroup\$
    – pimvdb
    Commented Dec 31, 2011 at 10:43
  • \$\begingroup\$ @M.Joanis: duh, thanks for noticing. Fixed. \$\endgroup\$ Commented Dec 31, 2011 at 12:30
  • 1
    \$\begingroup\$ I think you could spare a few characters if you switched to K&R C. If you're ok with that. \$\endgroup\$
    – J B
    Commented Dec 31, 2011 at 13:02
  • \$\begingroup\$ You could shorten this by four characters by moving the printf out of the loop. \$\endgroup\$
    – marinus
    Commented Jan 1, 2012 at 23:02
3
\$\begingroup\$

dc – 26 chars

This is rather long, mostly due to the lack of loop constructs in dc.

0?[d2%rsi+li2/d0<x]dsxx+p

Keeps adding up the modulo 2 of the number and dividing the number by to until it reaches zero. Can handle arbitrarily long integers.

Example:

$ dc -e '0?[d2%rsi+li2/d0<x]dsxx+p' <<< 127
7
$ dc countones.dc <<< 1273434547453452352342346734573465732856238472384263456458235374653784538469120235
138
\$\endgroup\$
3
\$\begingroup\$

C, 66 characters

main(int n,char **a){printf("%u",__builtin_popcount(atoi(a[1])))};

Note: requires gcc or gcc-compatible compiler (e.g. ICC, clang).

For some CPUs __builtin_popcount compiles to a single instruction (e.g. POPCNT on x86).

\$\endgroup\$
4
  • \$\begingroup\$ Is it correct that __builtin_popcount actually just implements the counting of 1s itself? If so, although it's not strictly wrong according to the rules I honestly don't think this is a fair entry. \$\endgroup\$
    – pimvdb
    Commented Jan 1, 2012 at 15:29
  • \$\begingroup\$ You should probably stipulate this in the question if you want to disallow entries that take advantage of built-in capabilities of a given language or compiler. \$\endgroup\$
    – Paul R
    Commented Jan 1, 2012 at 15:51
  • \$\begingroup\$ This is not legal C++ because in C++ you cannot omit the return type on main, nor use printf without prior include. \$\endgroup\$
    – celtschk
    Commented Feb 5, 2012 at 13:39
  • \$\begingroup\$ @celtschk: fair point - edited out the C++ \$\endgroup\$
    – Paul R
    Commented Feb 5, 2012 at 14:39
2
\$\begingroup\$

D (70 chars)

int f(string i){int k=to!int(i),r;while(k){if(k%2)r++;k/=2;}return r;}
\$\endgroup\$
2
\$\begingroup\$

JavaScript, 78 72 71 characters

I'll post my initial solution which I came up with before posting the question as well. There is already a much better JavaScript answer though :)

for(n=prompt(a=0),j=1;j<=n;j*=2)for(i=j;i<=n;i+=2*j)n<i+j&&a++;alert(a)

http://jsfiddle.net/Mk8zd/1/

The idea comes from certain "mind reading cards" which enable you to obtain the number someone else has in mind, by showing them cards and let them say on which cards their number is apparent.

It works because each number is a unique combination of 1s / 0s in binary. My solution checks on which "cards" the number is apparent so as to determine how many 1s it has. It's just not very efficient, though...

I found this document which outlines the mind reading technique.

\$\endgroup\$
2
\$\begingroup\$

Haskell (60 chars)

f n=sum[1|x<-[0..n],odd$n`div`2^x]
main=interact$show.f.read
\$\endgroup\$
2
\$\begingroup\$

PHP, 57

$i=$s=0;for(;$i<log($n,2);){$s+=$n/pow(2,$i++)%2;}echo$s;

This assumes that $n holds the value to be tested.

PHP, 55 (alternative solution)

function b($i){return$i|0?($i%2)+b($i/2):0;}echo b($n);

Again, this assumes that $n holds the value to be tested. This is an alternative because it uses the or-operator to floor the input.

Both solutions work and do not cause notices.

\$\endgroup\$
2
\$\begingroup\$

Ocaml, 45 characters

Based on @Leah Xue's solution. Three spaces could be removed and it's sligthly shorter (~3 characters) to use function instead of if-then-else.

let rec o=function 0->0|x->(x mod 2)+(o(x/2))  
\$\endgroup\$
2
\$\begingroup\$

Java 7, 36 bytes

int b(Long a){return a.bitCount(a);}

Because of course this, of all things, is something that Java has a builtin for...

\$\endgroup\$
4
  • \$\begingroup\$ Doesn't this fit under "built-in base-conversion functions", which are banned? \$\endgroup\$
    – FlipTack
    Commented Dec 16, 2016 at 20:22
  • \$\begingroup\$ @Flp.Tkc I'm not actually doing base-conversion. I have no idea how bitCount operates under the hood. \$\endgroup\$
    – Poke
    Commented Dec 16, 2016 at 20:29
  • \$\begingroup\$ this seems like just using a bulitin to do the job, but ok... \$\endgroup\$
    – FlipTack
    Commented Dec 16, 2016 at 20:30
  • \$\begingroup\$ @Flp.Tkc That's... exactly what it is? I'm even including all required libraries (there aren't any). This is demonstrating the strength of the language! related meta \$\endgroup\$
    – Poke
    Commented Dec 16, 2016 at 20:35
2
\$\begingroup\$

Mathematica 26

Count[n~IntegerDigits~2,1]
\$\endgroup\$
2
\$\begingroup\$

386 opcode, 10 Bytes

2BC0                       SUB EAX,EAX
01C9                       ADD ECX,ECX
1400                       ADC AL,0
41                         INC ECX
E2F9                       LOOP $-5
C3                         RET

Thank Peter Cordes for 1B save and 1B rule save

\$\endgroup\$
1
  • \$\begingroup\$ You can just write a function that returns a value in AL, avoiding the out. Also use 2-byte adc al, 0. But good use of inc/loop as a 3-byte replacement for test ecx,ecx/jnz. And BTW, you could include another version that does popcnt eax, ecx / ret, for CPUs with that feature. \$\endgroup\$ Commented Apr 28, 2020 at 23:19
2
\$\begingroup\$

Vyxal l, 49 bits1, 6.125 bytes

ʀEṗ'∑?=;f

Try it Online!

Brute force solution, so the online interpreter times out. May potentially be made shorter by porting others, but I thought this solution was fun

ʀ         # range 0..input+1
 E        # raise 2^n for each value in that range
  ṗ       # powerset
   '   ;  # filtered by
    ∑     # the sum
     ?=   # is equal to the input?
        f # flatten
          # after which the l flag takes the length of the top of the stack and implicitly outputs it
\$\endgroup\$
1
\$\begingroup\$

Scala, 86 characters

object O extends App{def f(i:Int):Int=if(i>0)i%2+f(i/2)else 0
print(f(args(0).toInt))}

Usage: scala O 56432

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

R, 53 characters

o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())

Examples:

> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 56432
2: 
Read 1 item
[1] 8
> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 45781254
2: 
Read 1 item
[1] 11
> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 0
2: 
Read 1 item
[1] 0

If inputting the number is not part of the character count, then it is 43 characters:

o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0}

with test cases

> o(56432)
[1] 8
> o(45781254)
[1] 11
> o(0)
[1] 0
\$\endgroup\$
1
\$\begingroup\$

OCaml, 52 characters

let rec o x=if x=0 then 0 else (x mod 2) + (o (x/2))
\$\endgroup\$
1
\$\begingroup\$

Scheme

I polished the rules a bit to add to the challenge. The function doesn't care about the base of the number because it uses its own binary scale. I was inspired by the way analog to numeric conversion works. I just use plain recursion for this:

(define (find-ones n)
  (define (nbits n)
    (let nbits ([i 2])
      (if (< i n) (nbits (* i 2)) i)))
  (let f ([half (/ (nbits n) 2)] [i 0] [n n])
    (cond [(< half 2) i]
      [(< n i) (f (/ half 2) i (/ n 2))]
      [else (f (/ half 2) (+ i 1) (/ n 2))])))
\$\endgroup\$
1
\$\begingroup\$

Isn't reading a number into binary or printing the number from binary a "builtin base conversion function", thus invalidating every answer above that prints an integer? If you permit reading and printing an integer, like almost all the above answers do, then I'll make claims using a builtin popcount function :

Haskell, 50

There was a popCount routine added to the Data.Bits module for GHC v7.2.1/v7.4.1 this summer (see tickets concerning the primop and binding).

import Data.Bits
main=interact$show.popCount.read

I cannot beat the above Python and Perl scores using their GMPY or GMP::Mpz modules for GMP sadly, although GMP does offer a popcount function too.

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

JavaScript, 57 55 51 50 bytes

a=prompt(b=0);while(a){b+=a%2;a=(a-a%2)/2}alert(b)

Modulo is not bitwise operator ☺

\$\endgroup\$
6
  • \$\begingroup\$ | is a bitwise operator... \$\endgroup\$
    – Jamie
    Commented Jul 8, 2015 at 3:49
  • \$\begingroup\$ I can't golf it further... \$\endgroup\$
    – Jamie
    Commented Jul 8, 2015 at 3:57
  • \$\begingroup\$ I think you can replace the while with a for. \$\endgroup\$
    – lirtosiast
    Commented Jul 8, 2015 at 4:10
  • \$\begingroup\$ The problem is how? I just don't know ;) \$\endgroup\$
    – Jamie
    Commented Jul 8, 2015 at 4:14
  • \$\begingroup\$ for(a=prompt(b=0);a;){...} \$\endgroup\$
    – hyperneutrino
    Commented Jul 17, 2017 at 22:32

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.