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

1

How to separate the digits of a number and add them, 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 did not quite understand how it was done.

    
asked by anonymous 21.04.2017 / 04:25

2 answers

0

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

soma = 0
numero = 123
while(numero > 0):
    soma += numero % 10
    numero = int(numero /10)
print(soma)
    
21.04.2017 / 05:37
0

Try 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)
    
21.04.2017 / 09:09