Sum the digits of a number

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

    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))
    

提交回复
热议问题