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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With