Home > Mobile >  How do I get the sums of digits of the negative large number in Haskell?
How do I get the sums of digits of the negative large number in Haskell?

Time:02-03

sumOfDigitsPosNeg x =
    if x == 0 then 0
    else if x < 0 then sumOfDigitsPosNeg ((-1)*x `div` 10)   mod ((-1)*x) 10 
    else sumOfDigitsPosNeg (x `div` 10)   mod x 10 

I've tried with these code, but if the input is more than one digit, the output is wrong. I'm just confused how to convert the negative numbers into positive. How do I approach this problem?

CodePudding user response:

Using abs this is quite easy. We just operate on the absolute value of the number input.

sumDigits :: Integral t => t -> t
sumDigits 0 = 0
sumDigits n = a `mod` 10   sumDigits (a `div` 10)
    where a = abs n

CodePudding user response:

You can work with a helper go function that will only retrieve the absolute value. We thus call go with the abs :: Num a => a -> a of the item:

sumOfDigitsPosNeg :: Integral a => a -> a
sumOfDigitsPosNeg = go . abs
    where go 0 = 0
          go n = r   go q
              where (q, r) = quotRem n 10
  •  Tags:  
  • Related