Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of 1 bits in a decimal number

Tags:

haskell

How can I write a function to return the number of 1 bits corresponding a decimal number? Maybe a square root function? The type should be this:

bits :: Int -> Int

EDIT: SOlved

uns :: Int -> Int
uns  0 = 0
uns 1 = 1
uns x | mod x 2 == 1 = 1 + uns (div x 2)
      | otherwise = uns (div x 2)
like image 344
Richard Avatar asked Nov 28 '25 00:11

Richard


1 Answers

What about this old trick?

import Data.Bits

countOnes 0 = 0
countOnes x = 1 + countOnes (x .&. (x-1))

It only recurses n times where n is the number of one bits in x.

Of course, if you are going to import Data.Bits, then you might as well use popCount as @Cirdec suggested.

like image 155
ErikR Avatar answered Nov 30 '25 12:11

ErikR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!