Fastest method for adding/summing the individual digit components of a number

后端 未结 4 622
无人及你
无人及你 2021-02-03 10:53

I saw a question on a math forum a while back where a person was discussing adding up the digits in a number over and over again until a single digit is achieved. (i.e. \"362\"

4条回答
  •  误落风尘
    2021-02-03 11:08

    Here's something in Haskell:

    sumDigits n = 
      if n == 0 
         then 0
         else let a = mod n 10
              in a + sumDigits (div n 10)
    

    Oh, but I just read you're doing that already...

    (then there's also the obvious:

    sumDigits n = sum $ map (read . (:[])) . show $ n
    

    )

提交回复
热议问题