Sum the digits of a number

后端 未结 18 2003
抹茶落季
抹茶落季 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条回答
  •  -上瘾入骨i
    2020-11-22 10:59

    def digitsum(n):
        result = 0
        for i in range(len(str(n))):
            result = result + int(str(n)[i:i+1])
        return(result)
    

    "result" is initialized with 0.

    Inside the for loop, the number(n) is converted into a string to be split with loop index(i) and get each digit. ---> str(n)[i:i+1]

    This sliced digit is converted back to an integer ----> int(str(n)[i:i+1])

    And hence added to result.

提交回复
热议问题