Sum the digits of a number

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

    I cam up with a recursive solution:

    def sumDigits(num):
    #   print "evaluating:", num
      if num < 10:
        return num
    
      # solution 1
    #   res = num/10
    #   rem = num%10
    #   print "res:", res, "rem:", rem
    #   return sumDigits(res+rem)
    
        # solution 2
      arr = [int(i) for i in str(num)]
      return sumDigits(sum(arr))
    
    # print(sumDigits(1))
    # print(sumDigits(49))
    print(sumDigits(439230))
    # print(sumDigits(439237))
    

提交回复
热议问题