Sum the digits of a number

后端 未结 18 2335
抹茶落季
抹茶落季 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:10

    Here is a solution without any loop or recursion but works for non-negative integers only (Python3):

    def sum_digits(n):
        if n > 0:
            s = (n-1) // 9    
            return n-9*s
        return 0
    

提交回复
热议问题