[ create a new paste ] login | about

Link: http://codepad.org/iugdbm48    [ raw code | output | fork | 1 comment ]

mohit_at_codepad - Haskell, pasted on Mar 27:
-- Written by Mohit Jain
-- Count number of set bits in number
import Data.Bits

countSetBits ::Integer -> Integer
countSetBits = helper 0 where
               helper acc 0   = acc
               helper acc num = helper nacc rnum where
                                nacc = succ acc
                                pnum = pred num
                                rnum = num .&. pnum -- Source of this LOC:
                                                    -- C Programming Language 2nd
                                                    -- Ed. (by Brian W. Kernighan
                                                    -- and Dennis M. Ritchie)
                                                    -- in exercise 2-9

main = performCountBitsOnList [0,                                         -- test 0 case
                               123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890,  -- testing some big number
                               81129638414606681695789005144064,          -- 2 ^ 106
                               39614081257132168796771975167,             -- 2 ^ 95 - 1
                               81129638414606681695789005144063] where    -- 2 ^ 106 - 1
       performCountBitsOnList = putStr . unlines . map show . map countSetBits
-- Expected output (0 408 1 95 106)


Output:
1
2
3
4
5
0
408
1
95
106


Create a new paste based on this one


Comments:
posted by mohit_at_codepad on Mar 27
Review email:
I got an email that expected output uses space, but my code prints one output per line.

Reply:
To get space separated output on one line, please replace "unlines" on line 22 with "unwords".
reply