Friday, 3 June 2016

Haskell: Reverse digits of a number


reverseDigits.hs
reverseData :: Integer -> Integer -> Integer
reverseData num rev
    | (num == 0) = rev
    | otherwise = (reverseData (num `div` 10) ((rev*10) + (num `rem` 10)))

{- Reverse digit of a number -}
reverseNumber :: Integer -> Integer
reverseNumber num
    | (num < 0) = ((-1) * reverseNumber ((-1) * num))
    | otherwise = reverseData num 0

*Main> :load reverseDigits.hs
[1 of 1] Compiling Main             ( reverseDigits.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> reverseNumber 123
321
*Main> 
*Main> reverseNumber (-123)
-321
*Main> 
*Main> reverseNumber 0
0
*Main> 
*Main> reverseNumber 9
9
*Main>



Previous                                                 Next                                                 Home

No comments:

Post a Comment