1. 程式人生 > >使用Haskell計算一個正整數二進位制表示中最大的連續的1的個數

使用Haskell計算一個正整數二進位制表示中最大的連續的1的個數

source: https://www.hackerrank.com/challenges/30-binary-numbers

module Main where


countMine :: Int -> Int -> Int
countMine c n | n == 0 = c
          | otherwise = let tup = count1 0 n
                        in if snd tup == n then countMine c (div n 2)
                           else countMine (max c (fst tup)) (snd tup)
          where count1 c n | mod n 2 == 0 = (c, n)
                           | otherwise = count1 (c+1) (div n 2)

main :: IO()
main = do
    n <- fmap read getLine :: IO Int
    print $ countMine 0 n
    return ()