Sum the digits of a number - python

2019-01-02 20:42发布

If I want to find the sum of the digits of a number, i.e. :

  • Input: 932
  • Output: 14, which is (9 + 3 + 2)

What is the fastest way of doing this?

I instinctively did:

sum(int(digit) for digit in str(number))

and I found this online:

sum(map(int, str(number)))

Which is best to use for speed, and are there any other methods which are even faster?

11条回答
素衣白纱
2楼-- · 2019-01-02 20:51

You can also use this:

def sum_digits(num):
    num = str(num)
    digitSum = 0
    for i in num:
        digitSum += int(i)
    return digitSum
print sum_digits(875)
查看更多
心情的温度
3楼-- · 2019-01-02 20:52
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

查看更多
明月照影归
4楼-- · 2019-01-02 20:52
n = str(input("Enter the number\n"))

list1 = []

for each_number in n:

        list1.append(int(each_number))

print(sum(list1))
查看更多
深知你不懂我心
5楼-- · 2019-01-02 20:53

You can try this

def sumDigits(number):
    sum = 0
    while(number>0):
        lastdigit = number%10
        sum += lastdigit
        number = number//10

    return sum
查看更多
大哥的爱人
6楼-- · 2019-01-02 20:54

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
查看更多
孤独寂梦人
7楼-- · 2019-01-02 20:54

you can also try this with built_in_function called divmod() ;

number = int(input('enter any integer: = '))
sum = 0
while number!=0: 
    take = divmod(number, 10) 
    dig = take[1] 
    sum += dig 
    number = take[0] 
print(sum) 

you can take any number of digit

查看更多
登录 后发表回答