Sum the digits of a number

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

    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

    0 讨论(0)
  • 2020-11-22 11:14

    The best way is to use math.
    I knew this from school.(kinda also from codewars)

    def digital_sum(num):
        return (num % 9) or num and 9
    

    Just don't know how this works in code, but I know it's maths

    If a number is divisible by 9 then, it's digital_sum will be 9,
    if that's not the case then num % 9 will be the digital sum.

    0 讨论(0)
  • 2020-11-22 11:17

    You can try this

    def sumDigits(number):
        sum = 0
        while(number>0):
            lastdigit = number%10
            sum += lastdigit
            number = number//10
    
        return sum
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 11:18

    Try this

        print(sum(list(map(int,input("Enter your number ")))))
    
    0 讨论(0)
  • 2020-11-22 11:21
    n = str(input("Enter the number\n"))
    
    list1 = []
    
    for each_number in n:
    
            list1.append(int(each_number))
    
    print(sum(list1))
    
    0 讨论(0)
提交回复
热议问题