Compute sum of digits of a number

Asked

Viewed 37,801 times

7

Type a program that receives an integer number in the input, calculate and print the sum of the digits of this number in the output. Example:

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

Tip: To separate digits, remember: the operator // makes an entire division by throwing away the rest, ie that which is less than the divisor; The operator % returns only the rest of the entire division by throwing away the result, that is, all that is greater than or equal to the divisor.

I tried several ways, but the result keeps giving zero. I only have this attempt noted because I’ve been doing 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)
  • 1-only bar is floating point division, you should use double bar (integer division); 2- not integer division, you do not need to subtract the rest

  • n = n//10 using the entire split operator without taking the rest

11 answers

17

If you want to explore alternative solutions, I propose one that escapes 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 eternal object. By default, the function input returns a string, which is iterable in Python. Since we want the algebraic sum of digits, just convert each one to the integer type.

See working on Repl.it or in the Ideone.

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

6

In order for your algorithm to work, you need to take the last digit of the number, and store this value somewhere, then remove this number from the original digit, and do so while 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 - Take the last digit of n;
2 - Sum this digit in variable s;
3 - Remove last digit of number n;
4 - Back to step 1;

  • I believe that also does not work for negative values, because it would be evaluated as false in the condition of while. Change to while n != 0 maybe it would solve the problem.

5

My solution similar to yours:

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

soma = 0

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

4

I’m behind in a couple of years, but in my solution, as the statement asked about numbers greater than zero, I made the implementation of a casual if that gives access to all the while in question, otherwise it just displays a message saying that the number is invalid.

 numero = int(input('numero: '))
    if numero > 0:
        soma = 0
        while numero != 0:
            resto = numero % 10
            numero = (numero - resto) // 10
            soma = soma + resto
        print(f'soma: {soma}')
    else:
        print('numero invalido...')

3

Just to give one more option, and mention a case that was only cited - but not solved - in other answers (when the number is negative):

# ajuste para o caso de n ser negativo
n = abs(n)

soma = 0
while n > 0:
    n, d = divmod(n, 10)
    soma += d

I use divmod, which already returns the result of the split and the rest of it in a tuple - a documentation says that for whole numbers the result of divmod(a, b) is the same as (a // b, a % b), then it is equivalent to doing these operations separately.


Other option - half over Engineered for this case - is to create a generator that returns the digits of the number, so I can use it with sum:

def digitos(n):
    n = abs(n)
    while n > 0:
        n, d = divmod(n, 10)
        yield d

n = int(input('Digite um número: '))
soma = sum(digitos(n))

2

I made this code very simple. I’m starting so I think it can help people who are also having this problem and are starting in python. I transformed parts of the string into integer.

x = input('Digite um número positivo maior que 0\n')
if int(x) > 0:
    i = 0
    s = 0
    while i < len(x):
        s = s + int(x[i])
        i = i + 1
    print(f'A soma dos números é: {s}')
else:
    print('Digite Valores Válidos')

2

I was also doubtful about this program, and based on your achievement by making 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)

0

An alternative is to use the function reduce() module functools

from functools import reduce

n = input("Digite um número inteiro: ")
print(reduce(lambda *args: sum(args), map(int, n), 0))
  • reduce() applies a two-argument function cumulatively to the items of an iterable so as to reduce the iterable to a single value.
  • lambda *args: sum(args) is an anonymous function that returns to summing up of his arguments.
  • map(int, n) applies the conversion to integer function to each digit of the string.

See the example on Ideone.com

0

Hello, I did this: hope it helps ;)

numero = int(input('Digite um número inteiro: '))
    
    if numero > 0:
            soma = 0
            while numero != 0:
                resto = numero % 10
                numero = (numero - resto) // 10
                soma = soma + resto
            print(soma)
    else: 
     print(numero)

0

def sum_alg(numero): # Função para somar os algarismos de um número
    a = 0
    for n in range(len(str(numero))):
        n = numero // 10 ** n % 10
        a = a + n
        n = n / 10
    print a

-4

n = int (input (“Digite um numero inteiro:”))
soma = 0
      while (n = 0):
               resto =numero % 10
               n = (n - resto) / / 10
              soma = soma + resto
printf (“A soma dos numeros e”, soma“)
else:

printf (“numero valido:”)
else:

print (“numero invalido:”)
  • 3

    Are you sure this is Python? Apart from some syntax errors, the function printf does not exist natively in the language.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.