Hello,
Does anyone know a way of taking digits of a number, putting into a list, and adding them together quicker than this?
while x>0:
t.append(x%10)
l+=x%10
x=(x-x%10)//10
In which 'l' is the sum, and x is the number.
I don't know if it's faster, but you could convert it to a string, read the digits, then convert those back to integers. This gets a list where element 0 is the MSD.
>>> x=5238
>>> l = [int(d) for d in str(x)]
>>> l
[5, 2, 3, 8]
For the math method,
divmod
would let you use fewer operations. This list is the same as your solution where element 0 is the LSD.
>>> x
5238
>>> l = []
>>> while x:
... x, remainder = divmod(x, 10)
... l.append(remainder)
...
>>> l
[8, 3, 2, 5]
If the objective is to get reversed integer then instead of list one can use integer right away:
>>> num = 5238
>>> reversed_num = 0
>>> while num:
... num, reminder = divmod(num, 10)
... reversed_num = reversed_num * 10 + reminder
...
>>> reversed_num
8325