r/dailyprogrammer • u/rya11111 3 1 • Apr 30 '12
[4/30/2012] Challenge #46 [easy]
The population count of a bitstring is the number of set bits (1-bits) in the string. For instance, the population count of the number 23, which is represented in binary as 10111 is 4.
Your task is to write a function that determines the population count of a number representing a bitstring
16
Upvotes
5
u/_redka 0 0 Apr 30 '12
4
u/Ttl May 01 '12
The fastest way using C and inline assembly. Uses popcnt instruction that was added in SSE4 instruction set, so this requires cpu with support for it.
4
u/[deleted] May 01 '12 edited May 01 '12
Brainfuck, assuming integer I/O:
Boring J function:
3
u/Zamarok Apr 30 '12
Haskell
2
u/[deleted] Apr 30 '12
2
u/[deleted] Apr 30 '12
My C++ Solution:
2
u/stinktank Apr 30 '12
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
2
u/luxgladius 0 0 Apr 30 '12
Perl one liner (though it could easily be C)
2
u/FataOne 0 0 May 01 '12
2
u/fuck-yeah-guy May 01 '12
My c# implementation:
2
u/xertoz May 01 '12
A PHP solution would be:
2
u/Cisphyx Apr 30 '12
Python:
1
u/robin-gvx 0 2 Apr 30 '12
As usual, two versions, the second without variables: http://hastebin.com/raw/wesuyaneyo
1
u/debugmonkey 0 0 Apr 30 '12
Let me know if you spot any issues or see a way to optimize. C++
1
u/Nedroo Apr 30 '12
Scala:
1
u/saijanai Apr 30 '12
In Pharo smalltalk:
(23 bitString asArray select:[:bit| bit = $1]) size.
also works for Large Integers, eg:
(2300 factorial bitString asArray select:[:bit| bit = $1]) size.
as well as negative Large Integers:
(-2300 factorial bitString asArray select:[:bit| bit = $1]) size.
1
u/[deleted] May 01 '12 edited May 01 '12
JavaScript -- any feedback is very very welcome! The program will query you for an input number.
Can be run here easily in your browser http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_abs
1
u/jonzo1 0 0 May 01 '12
Clojure:
1
u/whydoyoulook 0 0 May 01 '12 edited May 01 '12
Okay. So I haven't programmed a thing in quite some time and I'm trying to get back into it. I'm sure there are more elegant ways, but here's my Java solution:
1
u/xxNIRVANAxx 0 0 May 01 '12 edited May 01 '12
Using C today
1
u/foopq May 01 '12
Haskell
1
u/HazzyPls 0 0 May 02 '12
Can't touch inline assembly, but I still like it.
1
u/school_throwaway May 02 '12
python
1
u/[deleted] May 03 '12
Javascript:
1
u/JerMenKoO 0 0 May 05 '12
Python 3.x
1
u/verydapeng May 08 '12
most of the answers here do not address negative numbers
0
u/[deleted] Apr 30 '12
[deleted] — view deleted comment