Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Digits of a number
#1
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.
Reply
#2
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]
Reply
#3
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Photo How can I use 2 digits format for all the number? plumberpy 6 2,344 Aug-09-2021, 02:16 PM
Last Post: plumberpy
  Single digits seem to be greater than double digits Frosty_GM 4 3,510 Nov-20-2020, 10:13 AM
Last Post: DeaD_EyE
  Please support regex for version number (digits and dots) from a string Tecuma 4 3,192 Aug-17-2020, 09:59 AM
Last Post: Tecuma
  summing digits of a number Megabeaz 3 2,656 Jun-29-2018, 02:55 PM
Last Post: ichabod801
  Input a number with any number of digits and output it in reverse order of digits. sarada2099 6 6,663 Mar-12-2017, 05:45 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020