Print the amount of ones in a binary number without using bitwise operators

14

5

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

pimvdb

Posted 2011-12-30T15:15:47.207

Reputation: 821

Are functions allowed? I want to make a Java solution, but writing full code is too tedious... :/ – HyperNeutrino – 2016-02-13T02:40:31.957

1

I guess I won't be using Wise for this challenge... :)

– MildlyMilquetoast – 2017-03-31T17:17:27.583

Answers

16

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.)

Dillon Cower

Posted 2011-12-30T15:15:47.207

Reputation: 2 192

2Doesn't this break the Built-in base conversion functions contraint? – Gareth – 2011-12-30T21:18:45.637

Whoops! Missed that one. – Dillon Cower – 2011-12-30T21:19:17.727

Gah! Thought I'd given myself a fighting chance with my J program! :-) Nice job. – Gareth – 2011-12-30T23:01:24.680

@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. :) – Dillon Cower – 2011-12-31T00:42:13.697

11

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.

lirtosiast

Posted 2011-12-30T15:15:47.207

Reputation: 20 331

9I knew it must have existed, but it took me an hour of sorting through Brainfuck derivatives on Esolang to find Brainbool. – lirtosiast – 2015-07-08T02:17:25.783

8

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)

Gareth

Posted 2011-12-30T15:15:47.207

Reputation: 11 678

I'll be happy to upvote this once it reads from stdin (or whatever equivalent J has). – Steven Rumbalski – 2011-12-30T18:51:21.050

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? – Gareth – 2011-12-30T21:18:35.620

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! – pimvdb – 2011-12-30T22:21:38.053

@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... – Gareth – 2011-12-30T22:59:52.827

...and having read some more I now see that I was completely wrong about standard input. – Gareth – 2011-12-31T10:02:51.970

I declined on this one. J's got a 2-char convert-to-base-two verb, and nobody would agree on whether that counts as a bitwise operation or not. (J 4-char answer would then be: +/#.) – J B – 2011-12-31T13:06:24.440

@J B Conversion functions are disallowed. – FUZxxl – 2012-01-02T21:36:13.737

@Gareth You can use the !: verb. IIRC input from stdin was 2!:1 and output was 2!:2 or something similar. – FUZxxl – 2012-01-02T21:36:50.663

8

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
  [-<<<<+>>>>]
  <<<<
]

copy

Posted 2011-12-30T15:15:47.207

Reputation: 6 466

6

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.

Steven Rumbalski

Posted 2011-12-30T15:15:47.207

Reputation: 1 353

6

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.

Howard

Posted 2011-12-30T15:15:47.207

Reputation: 23 109

5

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;).

Howard

Posted 2011-12-30T15:15:47.207

Reputation: 23 109

5

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.

Mr. Llama

Posted 2011-12-30T15:15:47.207

Reputation: 2 387

4

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.

PhiNotPi

Posted 2011-12-30T15:15:47.207

Reputation: 26 739

You might use $n=int($n/2) which 2 characters shorter. – Howard – 2011-12-30T16:28:08.783

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? ;) – user606723 – 2011-12-30T19:17:29.803

@user606723 I just tried that out and it seems to work perfectly, at least for every case up to 1000. – PhiNotPi – 2011-12-30T20:38:12.043

4

Python 2.6, 45 characters

b=lambda n:n and n%2+b(n/2) 
print b(input())

Steven Rumbalski

Posted 2011-12-30T15:15:47.207

Reputation: 1 353

You don't need the print b(input()). It is acceptable to return the value and take "input" as arguments for functions. – caird coinheringaahing – 2017-03-31T14:27:17.703

1Can be shortened by two characters by using def instead of a lambda. – Konrad Rudolph – 2011-12-31T11:51:00.623

1@KonradRudolph: Actually, you lose the advantage once you include the return statement. – Steven Rumbalski – 2011-12-31T18:02:54.467

Oops, I forgot that. Stupid. – Konrad Rudolph – 2011-12-31T18:06:15.630

3

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.

Ilmari Karonen

Posted 2011-12-30T15:15:47.207

Reputation: 19 513

Shouldn't the command-line arg be part of the char count? – Soham Chowdhury – 2013-05-03T10:35:24.473

@SohamChowdhury: Not per this meta thread.

– Ilmari Karonen – 2013-05-03T13:59:11.180

Does the $= special variable do anything special in your program, or is it just another ordinary variable? – PhiNotPi – 2011-12-30T20:47:28.543

2@PhiNotPi: $= only takes integer values, so using it saves me an int. – Ilmari Karonen – 2011-12-30T21:11:29.807

3

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

sam hocevar

Posted 2011-12-30T15:15:47.207

Reputation: 581

Why void? Let f be implicitly int (5 chars). Also, f(x,i) defines i, and there's no problem calling f(5) (2 chars). EDIT - noticed GigaWatt's answer, which does exactly this. – ugoren – 2012-01-29T21:46:46.883

I see bitwise!!! – Joanis – 2011-12-31T06:51:17.060

I'm sorry but the AND operator also counts as a bitwise operator. – pimvdb – 2011-12-31T10:43:07.270

@M.Joanis: duh, thanks for noticing. Fixed. – sam hocevar – 2011-12-31T12:30:12.213

1I think you could spare a few characters if you switched to K&R C. If you're ok with that. – J B – 2011-12-31T13:02:14.557

You could shorten this by four characters by moving the printf out of the loop. – marinus – 2012-01-01T23:02:48.440

@marinus: good catch; that's only 3 characters unfortunately since it requires to put the declaration of i out of the loop, too. – sam hocevar – 2012-01-02T02:01:09.033

3

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.)

Joanis

Posted 2011-12-30T15:15:47.207

Reputation: 291

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.

– pimvdb – 2011-12-31T12:31:20.097

3

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).

Paul R

Posted 2011-12-30T15:15:47.207

Reputation: 2 893

This is not legal C++ because in C++ you cannot omit the return type on main, nor use printf without prior include. – celtschk – 2012-02-05T13:39:32.653

@celtschk: fair point - edited out the C++ – Paul R – 2012-02-05T14:39:19.260

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. – pimvdb – 2012-01-01T15:29:12.730

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. – Paul R – 2012-01-01T15:51:56.970

3

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

daniero

Posted 2011-12-30T15:15:47.207

Reputation: 17 193

2

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.

pimvdb

Posted 2011-12-30T15:15:47.207

Reputation: 821

2

Haskell (60 chars)

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

marinus

Posted 2011-12-30T15:15:47.207

Reputation: 30 224

2

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.

Arjan

Posted 2011-12-30T15:15:47.207

Reputation: 121

2

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))  

ReyCharles

Posted 2011-12-30T15:15:47.207

Reputation: 525

2

Mathematica 26

Count[n~IntegerDigits~2,1]

DavidC

Posted 2011-12-30T15:15:47.207

Reputation: 24 524

1

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...

Poke

Posted 2011-12-30T15:15:47.207

Reputation: 3 075

Doesn't this fit under "built-in base-conversion functions", which are banned? – FlipTack – 2016-12-16T20:22:23.153

@Flp.Tkc I'm not actually doing base-conversion. I have no idea how bitCount operates under the hood. – Poke – 2016-12-16T20:29:42.210

this seems like just using a bulitin to do the job, but ok... – FlipTack – 2016-12-16T20:30:50.837

@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

– Poke – 2016-12-16T20:35:55.557

1

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

pizzapants184

Posted 2011-12-30T15:15:47.207

Reputation: 3 174

Welcome to the site! – James – 2017-03-31T16:59:13.107

1

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.

jstnthms

Posted 2011-12-30T15:15:47.207

Reputation: 181

Welcome to the site! :) – James – 2017-07-20T19:35:33.970

1

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 :(

mellamokb

Posted 2011-12-30T15:15:47.207

Reputation: 5 544

Input 1 gives output 0. – Atreys – 2012-01-31T16:50:24.973

1| is bitwise operator... it is disallowed. Time to do Math.round :-) – Jamie – 2015-07-08T04:02:42.767

3Isn't the |0 a bitwise operator? – Vilx- – 2012-01-02T15:36:29.920

Technically yes. But i'm using it purely to round to the nearest int, so I'm not getting any bit-wise benefit :) – mellamokb – 2012-01-03T16:36:16.547

Smells like bending the rules to me... but I'm not the judge. – Vilx- – 2012-01-04T08:46:18.203

1

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

Gareth

Posted 2011-12-30T15:15:47.207

Reputation: 11 678

1

D (70 chars)

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

ratchet freak

Posted 2011-12-30T15:15:47.207

Reputation: 1 334

1

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

Brian Diggs

Posted 2011-12-30T15:15:47.207

Reputation: 396

1

OCaml, 52 characters

let rec o x=if x=0 then 0 else (x mod 2) + (o (x/2))

Leah Xue

Posted 2011-12-30T15:15:47.207

Reputation: 111

1

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))])))

Samuel Duclos

Posted 2011-12-30T15:15:47.207

Reputation: 136

1

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.

Jeff Burdges

Posted 2011-12-30T15:15:47.207

Reputation: 445

0

GolfScript - 21

~{.2%{0):0;}*2/.}do;0

aditsu quit because SE is EVIL

Posted 2011-12-30T15:15:47.207

Reputation: 22 326

0

Python 2, 25 bytes

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

Try it online!

Koishore Roy

Posted 2011-12-30T15:15:47.207

Reputation: 1 144

0

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.

FlipTack

Posted 2011-12-30T15:15:47.207

Reputation: 13 242

0

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!

Giuseppe

Posted 2011-12-30T15:15:47.207

Reputation: 21 077

0

386 opcode, 12 Bytes

2BC0                       SUB EAX,EAX
01C9                       ADD ECX,ECX
83D000                     ADC EAX,0
41                         INC ECX
E2 F8                      LOOP $-6
EE                         OUT EDX,AL ; assuming it's a display port ...
C3                         RET

l4m2

Posted 2011-12-30T15:15:47.207

Reputation: 5 985

0

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

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

l4m2

Posted 2011-12-30T15:15:47.207

Reputation: 5 985

0

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.

Bolce Bussiere

Posted 2011-12-30T15:15:47.207

Reputation: 970

0

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

Jo King

Posted 2011-12-30T15:15:47.207

Reputation: 38 234

0

><>, 20 bytes

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

Try it online!

Emigna

Posted 2011-12-30T15:15:47.207

Reputation: 50 798

0

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).

Sophia Lechner

Posted 2011-12-30T15:15:47.207

Reputation: 1 200

0

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

reffu

Posted 2011-12-30T15:15:47.207

Reputation: 1 361

0

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)

maxb

Posted 2011-12-30T15:15:47.207

Reputation: 5 754

0

Python (48 without spaces, 65 with)

x = int(raw_input())
s = 0
while x:
    if x%2:
        s+=1
    x/=2
print s

elssar

Posted 2011-12-30T15:15:47.207

Reputation: 579

My first ever submission on CodeGolf. Wish I had thought of eliminating the if before I saw @Steve Rumbalski's answer – elssar – 2011-12-30T17:43:14.307

0

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

Ry-

Posted 2011-12-30T15:15:47.207

Reputation: 5 283

0

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 ☺

Jamie

Posted 2011-12-30T15:15:47.207

Reputation: 166

| is a bitwise operator... – Jamie – 2015-07-08T03:49:43.303

I can't golf it further... – Jamie – 2015-07-08T03:57:31.363

I think you can replace the while with a for. – lirtosiast – 2015-07-08T04:10:18.637

The problem is how? I just don't know ;) – Jamie – 2015-07-08T04:14:52.783

for(a=prompt(b=0);a;){...} – HyperNeutrino – 2017-07-17T22:32:56.413

for(a=prompt(b=0);a;a=(a-a%2)/2)b+=a%2;alert(b) – l4m2 – 2017-12-28T14:55:38.517

0

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

Toby Speight

Posted 2011-12-30T15:15:47.207

Reputation: 5 058

0

excel, 35

=LEN(A1)-LEN(SUBSTITUTE(A1,"1",""))

SeanC

Posted 2011-12-30T15:15:47.207

Reputation: 1 117

1This 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) – Taylor Scott – 2017-03-25T19:16:07.317