Sum the digits of a number

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

    num = 123
    dig = 0
    sum = 0
    while(num > 0):
      dig = int(num%10)
      sum = sum+dig
      num = num/10
    

    print(sum) // make sure to add space above this line

提交回复
热议问题