Sum the digits of a number

后端 未结 18 2226
抹茶落季
抹茶落季 2020-11-22 10:52

If I want to find the sum of the digits of a number, i.e.:

  • Input: 932
  • Output: 14, which is (9 + 3 + 2)
18条回答
  •  一个人的身影
    2020-11-22 11:14

    The best way is to use math.
    I knew this from school.(kinda also from codewars)

    def digital_sum(num):
        return (num % 9) or num and 9
    

    Just don't know how this works in code, but I know it's maths

    If a number is divisible by 9 then, it's digital_sum will be 9,
    if that's not the case then num % 9 will be the digital sum.

提交回复
热议问题