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

1
2
1
\$\begingroup\$

sed, 100 bytes

:
s/[13579]/&;/g
y/123456789/011223344/
s/;0/5/g
s/;1/6/g
s/;2/7/g
s/;3/8/g
s/;4/9/g
/[1-9]/b
s/0//g

Output is in unary; if you want it in decimal, pipe through wc -c or append the following converter (GNU sed -r):

# unary to decimal
:d
s/;;;;;/v/g
s/vv/x/g
s/x([0-9]|$)/x0\1/
s/;;/b/g
s/bb/4/
s/b;/3/
s/v;/6/
s/vb/7/
s/v3/8/
s/v4/9/
y/;bvx/125;/
td

This implements successive division by 2, accumulating carry-out as output. It is able to handle fairly large inputs; for example I tested the all-ones 8192-bit input thus:

$ dc <<<'2 8192^1-p' | tr -d '\\\n' | ./4434.sed | wc -c
8192

and the mostly-zeros of similar length:

$ dc <<<'2 8192^p' | tr -d '\\\n' | ./4434.sed | wc -c
1
\$\endgroup\$
1
\$\begingroup\$

JavaScript, 49 47 45 42 bytes

for(n=prompt(o=0);n=n/2|0;o+=n%2);alert(o)

Demo: http://jsfiddle.net/hcYdx/4/

Edit 1: remove q and use ~~ for rounding, save 2 chars.

Edit 2: use |0 rounding operator instead of ~~ to save parentheses (2 chars).

Edit 3: simplify n>0 to n and combine with n=n/2|0 to make entire condition; now have wasted statement space :(

\$\endgroup\$
5
  • 3
    \$\begingroup\$ Isn't the |0 a bitwise operator? \$\endgroup\$
    – Vilx-
    Commented Jan 2, 2012 at 15:36
  • \$\begingroup\$ Technically yes. But i'm using it purely to round to the nearest int, so I'm not getting any bit-wise benefit :) \$\endgroup\$
    – mellamokb
    Commented Jan 3, 2012 at 16:36
  • \$\begingroup\$ Smells like bending the rules to me... but I'm not the judge. \$\endgroup\$
    – Vilx-
    Commented Jan 4, 2012 at 8:46
  • \$\begingroup\$ Input 1 gives output 0. \$\endgroup\$
    – Atreys
    Commented Jan 31, 2012 at 16:50
  • 1
    \$\begingroup\$ | is bitwise operator... it is disallowed. Time to do Math.round :-) \$\endgroup\$
    – Jamie
    Commented Jul 8, 2015 at 4:02
1
\$\begingroup\$

TI-Basic (TI-84 Plus CE), 30 bytes

Prompt X
0→S
While X
S+remainder(2,X→S
int(X/2→X
End
S

TI-Basic is a tokenized language, all tokens but remainder( are one-byte, remainder is two

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to the site! \$\endgroup\$
    – DJMcMayhem
    Commented Mar 31, 2017 at 16:59
1
\$\begingroup\$

PHP, 36 bytes

while($n){$o+=$n%2;$n/=2*1;}echo $o;

Assumes $n is the number to be tested, shows a PHP Notice for $o, and doesn't exactly work when $n is 0 (outputs nothing).

PHP, 53 bytes

$n=$argv[1];$o=0;while($n){$o+=$n%2;$n/=2*1;}echo $o;

Accepts command-line input, doesn't show a PHP Notice, and outputs correctly for 0.

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to the site! :) \$\endgroup\$
    – DJMcMayhem
    Commented Jul 20, 2017 at 19:35
1
\$\begingroup\$

Forth (gforth), 37 bytes

: f dup 0> if 2 /mod recurse + then ;

Try it online!

Usually recursion isn't worth it when golfing Forth because it requires the if, then, (possible else), and recurse words. In this case we can do without else and we save more in stack-manipulation than we lose from recursion

Explanation

  • If n is greater than 0, get quotient and remainder of dividing n by 2.
  • Call recursively on quotient
  • Add remainder to result

Code Explanation

: f         \ start new word definition
  dup       \ duplicate top stack value
  0> if     \ if top stack value is greater than 0
    2 /mod  \ get quotient and remainder of dividing by 2 (quotient on top of stack)
    recurse \ execute current word
    +       \ add remainder to result of recursion
  then      \ end if statement
;           \ end word definition
\$\endgroup\$
1
\$\begingroup\$

MathGolf, 12 bytes

æ_╫`¡▲ÞĽ↑;î

Try it online!

This fails for input 0, due to a bug in MathGolf. I'll explain why. But I thought it was a fun solution to this problem that might not be obvious.

This method could be seen as disallowed, but I refer to wikipedia: "The bit shifts are sometimes considered bitwise operations, because they treat a value as a series of bits rather than as a numerical quantity" (emphasis mine). I have chosen to interpret this to mean that MathGolf's bitshifts are allowed, since they don't operate on a fixed number of bytes. Bit rotating in MathGolf wraps the current number of bits in the number, and rotates using the bit width of the number. Thus, if you do this enough times, any number with \$n\$ set bits will converge to \$2^n-1\$. If you then divide the result by 2 until you reach 0, the number of divisions will represent the number of ones in the original number.

The reason that this fails for 0 is that 0 is somehow turned into 1 when left-rotated. This is a bug in the implementation of the operator, rather than this program itself, and should be fixed in an upcoming update.

Explanation

æ    ▲         do-while true using 4 operators
 _             duplicate TOS
  ╫            left-rotate bits in int, list/str
   `           duplicate the top two items
    ¡          push a, b, push a != b
               This do-while loop repeats until the left-rotated
      Þ        not implemented yet
       Ä       start block of length 1
        ½      pop a : push(a//2 if int else a/2)
         ↑     while true without popping
          ;    discard TOS
           î   index of current loop (1-based)
\$\endgroup\$
1
\$\begingroup\$

awk, 65 bytes

__=$(_^=___=_<_){++_;do{___+=__%_}while(__=int(__/_))}$!NF=___ ""

Example:

echo "56432\n45781254\n0" | 

mawk '__=$(_^=___=_<_){++_;do{___+=__%_}while(__=int(__/_))}$!NF=___ ""'

8
11
0
\$\endgroup\$
1
\$\begingroup\$

Thunno 2 L, 8 bytes

LOʠæS=;Ḟ

Port of emirps's Vyxal answer.

Explanation

LOʠæS=;Ḟ  # Implicit input
LO        # Push 2 ** [0..input)
  ʠ       # Powerset of this list
   æ  ;   # Filtered by:
    S=    #  Sum equals the input
       Ḟ  # Flatten this list of lists
          # L flag gets the length
          # Implicit output

Screenshot

Screenshot

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

Python (48 without spaces, 65 with)

x = int(raw_input())
s = 0
while x:
    if x%2:
        s+=1
    x/=2
print s
\$\endgroup\$
1
  • \$\begingroup\$ My first ever submission on CodeGolf. Wish I had thought of eliminating the if before I saw @Steve Rumbalski's answer \$\endgroup\$
    – elssar
    Commented Dec 30, 2011 at 17:43
0
\$\begingroup\$

Op, 23 19 (discontinued language of my invention)

0N[1~!?@2%{1+}2/])I

Here's a commented version:

0 # push a 0 onto the stack
N # read an integer from STDIN onto the stack
[ # begin an infinite loop
    1 # push a 1 onto the stack
    ~ # pop the 1 off the stack, and duplicate the top 1 items (i.e. the read number)
    ! # pop a number, push 1 if 0 or 0 otherwise (NOT)
    ? # pop a number, if the number is nonzero...
    @ # ... then break out of the infinite loop. Basically, break out when N reaches 0.
    2 # push a 2 onto the stack
    % # pop number "a" off the stack, then number "b", and push b modulo a.
    { # rotate the stack left
    1 # push a 1 onto the stack
    + # pop a and b, and push a + b (increment)
    } # rotate the stack right
    2 # push a 2 onto the stack
    / # pop number "a" off the stack, then number "b", then push b / a (int)
] # repeat back to start of loop
) # shift the stack right, taking off the 0 and leaving only the result
I # output the result as a number to STDOUT
\$\endgroup\$
0
\$\begingroup\$

excel, 35

=LEN(A1)-LEN(SUBSTITUTE(A1,"1",""))
\$\endgroup\$
1
  • 1
    \$\begingroup\$ This solution only provides the number of non-zero symbols in an input, and does not provide for the conversion to base 2, meaning that for the input 511 this provides the output 1 rather than the output 9. You should compare your output to that of =LEN(SUBSTITUTE(DEC2BIN(A1),0,)) (which is disallowed because of the builtin function DEC2BIN) \$\endgroup\$ Commented Mar 25, 2017 at 19:16
0
\$\begingroup\$

GolfScript - 21

~{.2%{0):0;}*2/.}do;0
\$\endgroup\$
0
\$\begingroup\$

Python 2, 25 bytes

lambda n:n and n%2+f(n/2)

Try it online!

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

Pushy, 12 bytes

$&2%v2/;O_S#

Try it online!

While the input is bigger than 0, it has its least significant bit (using mod) pushed to the second stack, then it is halved (integer division). Once all bits have been placed on the second stack, it is summed and the result is printed.

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

SNOBOL4 (CSNOBOL4), 66 bytes

	X =INPUT
I	O =O + REMDR(X,2)
	X =GT(X) X / 2	:S(I)
	OUTPUT =O
END

Try it online!

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

JavaScript, 43 Bytes, assuming 1/2/2/2/...=0

for(a=prompt(b=0);a;a/=2)b+=a%2>=1;alert(b)
\$\endgroup\$
0
\$\begingroup\$

J, 32 Bytes

There's probably a more mathematical way to do this that doesn't require finding the binary representation, but I thought this was pretty good none the less:

+/@:((}:,(|~2:)@{:,<.@-:@{:)^:])

Explanation:

+/@:((}:,(|~2:)@{:,<.@-:@{:)^:])  | Full program
    (                          )  | Convert to binary list:
     (                     )^:]   | do n times:
      }:                            | Curtail the list
        ,(|~2:)@{:                  | Append the remainder mod 2 of the item dropped
                  ,<.@-:@{:       | Append the floor of half the item dropped
+/@:                                | Sum

A step by step example:

    (}:,(|~2:)@{:,<.@-:@{:) 7
1 3
^ ^
| | 
| Floor 7/2
7 % 2

    (}:,(|~2:)@{:,<.@-:@{:) 1 3
1 1 1
^ ^ ^
| | |
| | Floor 3/2
| 3 % 2
The input curtailed

    ((}:,(|~2:^#)@{:,<.@-:@{:)^:]) 7
1 1 1 0 0 0 0 0

    +/@:((}:,(|~2:)@{:,<.@-:@{:)^:]) 7
3

Of course, you would only have to do this Ceil(log2 n) times, but thats a lot harder to calculate than just n.

\$\endgroup\$
1
  • \$\begingroup\$ Make sure you’re not using a built-in base converter, as that is forbidden in the challenge specifications. \$\endgroup\$ Commented May 9, 2023 at 18:16
0
\$\begingroup\$

brainfuck, 34 bytes

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

Try it online!

At 53 bytes, I thought the existing brainfuck solution was way too long /s. Starting cell contains the number and ends on the number of binary digits in it. Doesn't work for numbers above 255 unless you use an interpreter with larger than 8 bit or infinite cells.

How It Works

>+<[[>-]++[>]+[<]>-] Converts the number to binary
>[-<[->+<]>>]<       Adds all the numbers in the binary together
\$\endgroup\$
0
\$\begingroup\$

><>, 20 bytes

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

Try it online!

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

dc, 14 bytes

[2~rd0<M+]dsMx

Try it online!

Input is taken from the stack, output is left on the stack. This is the same general idea as the previous dc entry (repeatedly reduce mod 2 and add remainders), but optimizing by using non-tail recursion makes a huge difference (I'd have made this a comment on that entry, but the user hasn't been active for over a year).

\$\endgroup\$
1
2

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.