Sum the digits of a number

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

    This might help

    def digit_sum(n):
        num_str = str(n)
        sum = 0
        for i in range(0, len(num_str)):
            sum += int(num_str[i])
        return sum
    

提交回复
热议问题