Calculate sum of digits of a number

2

Write a program that receives an integer in the input, computes and prints the sum of the digits of this number in the output. Example:

>>> Digite um número inteiro: 123
6

Tip: To separate the digits, remember: the // operator makes a whole division throwing away the rest, ie, that which is smaller than the divisor; The % operator returns only the rest of the integer division by throwing out the result, that is, everything that is greater than or equal to the divisor.

I have tried in many ways, but the result continues to give zero. I only have this attempt annotated because I've been doing it over:

n = int(input("Digite um número inteiro: "))

soma = 0

while (n > 0):

    resto = n % 10
    n = (n - resto)/10
    soma = soma + resto


print("A soma dos números é: ", n)
    
asked by anonymous 31.03.2017 / 03:33

4 answers

7

If you want to explore alternative solutions, I suggest one that runs away from the hint of the statement.

n = input("Digite um número inteiro: ")

print(sum(int(i) for i in n))

The native function sum computes the sum of the items of an iterable object. By default, the input function returns a string, which is iterated in Python. Since we want the algebraic sum of the digits, simply convert each one to the integer type.

See working at Repl.it or Ideone .

  

Note : It works only for positive integer values, since treating the value as string , the minus sign is considered as a character.

    
31.03.2017 / 04:42
1

For your algorithm to work, you must take the last digit of the number, and store this value somewhere, then remove this number from the original digit, and do so as long as you have digits in the number.

def somar_digitos(n):
    s = 0
    while n:
        s += n % 10 # Soma 's' ao ultimo numeral de 'n'
        n //= 10 # Remove o ultimo numero de 'n'
    return s

What this algorithm does is simple:
1 - Get the last digit of n ;
2 - Add this digit in the variable s ;
3 - Remove the last digit of the number n ;
4 - Return to step 1;

    
01.04.2017 / 04:34
1

My solution looks like yours:

x = int(input("Numero: "))

soma = 0

while (x != 0):
    resto = x % 10
    x = (x - resto)//10
    soma = soma + resto
print(soma)
    
11.05.2017 / 22:12
0

I was also in doubt about this program, and based on yours I made the adjustments below.

n = int(input("Digite um número inteiro: "))

soma = 0

while (n > 0):

    resto = n % 10
    n = n // 10
    soma = soma + resto


print("A soma dos números é: ", soma)
    
24.10.2017 / 18:18