Sum the digits of a number

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

    If you want to keep summing the digits until you get a single-digit number (one of my favorite characteristics of numbers divisible by 9) you can do:

    def digital_root(n):
        x = sum(int(digit) for digit in str(n))
        if x < 10:
            return x
        else:
            return digital_root(x)
    

    Which actually turns out to be pretty fast itself...

    %timeit digital_root(12312658419614961365)
    
    10000 loops, best of 3: 22.6 µs per loop
    

提交回复
热议问题