If I want to find the sum of the digits of a number, i.e.:
93214, which is (9 + 3 + 2)
A base 10 number can be expressed as a series of the form
a × 10^p + b × 10^p-1 .. z × 10^0
so the sum of a number's digits is the sum of the coefficients of the terms.
Based on this information, the sum of the digits can be computed like this:
import math
def add_digits(n):
# Assume n >= 0, else we should take abs(n)
if 0 <= n < 10:
return n
r = 0
ndigits = int(math.log10(n))
for p in range(ndigits, -1, -1):
d, n = divmod(n, 10 ** p)
r += d
return r
This is effectively the reverse of the continuous division by 10 in the accepted answer. Given the extra computation in this function compared to the accepted answer, it's not surprising to find that this approach performs poorly in comparison: it's about 3.5 times slower, and about twice as slow as
sum(int(x) for x in str(n))