Sum the digits of a number

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

    Found this on one of the problem solving challenge websites. Not mine, but it works.

    num = 0            # replace 0 with whatever number you want to sum up
    print(sum([int(k) for k in str(num)]))
    

提交回复
热议问题