How to separate the digits of an integer and add them together? - Python

Asked

Viewed 10,535 times

3

How to separate the digits of a number and add them up, for example: 123 -> 1 + 2 + 3 = 6

How to do this, however, do this using arithmetic operators. I saw a case where it was separated using operations with "/" and "%", but I didn’t understand very well how it is done.

2 answers

1


You can do this way start with a variable for the sum using a loop to interact the digits of the number given in the example 123 at each step and do the division removing the rest of the division of the number by 10 with that extracted the last number %10 rest of the division 3 then divide the number by 10 with result 12 then restart the loop 12 % 10 rest of division 2 in case already adding with the number 3 and so on.

soma = 0
numero = 123
while(numero > 0):
    soma += numero % 10
    numero = int(numero /10)
print(soma)
  • Thank you, that’s exactly what I was looking for. Unfortunately I can’t vote, I don’t have 15 reputation yet.

0

Try it like this:

soma = 0
a = 123
b = str(a) #Transformo em str para poder usar posição. Ex: "b[1] = 2"
for i in range(len(b)):
        soma += int(b[i])
print(soma)
  • 1

    Hello Antony, I think the AP does not want this way. Anyway, I show you an alternative way to your: http://ideone.com/IR0jH5

Browser other questions tagged

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