Home > front end >  How to output the first digit of a number even if it's negative?
How to output the first digit of a number even if it's negative?

Time:05-12

In haskell, I used the following to get the first digit of postive numbers:

firstDigit :: Int -> Int
firstDigit n
    | n < 10    = n
    | otherwise = firstDigit (div n 10)

How could I solve the case for negative numbers? Would I just have to check for them before running the rest of the program or is there something more intuitive?

CodePudding user response:

You can first make a call with abs and then use a recursive function, so:

firstDigit :: Int -> Int
firstDigit = go . abs
    where go n | n < 10 = n
               | otherwise = go (div n 10)

CodePudding user response:

If you're okay with the "first digit" of a negative number being itself negative, then one way would be to keep dividing all the way to 0 and then back up one step.

firstDigit :: Int -> Int
firstDigit n = case n `quot` 10 of
    0 -> n
    n' -> firstDigit n'

This keeps the same code shape as your original, and doesn't require an extra check for negativity as the first step (not even hidden behind a call to abs). You do need to switch from div (which rounds down) to quot (which rounds towards zero) -- though you probably want to do that anyway if you don't take this approach, as it's marginally faster on most computers.

  • Related