Skip to content Skip to sidebar Skip to footer

How Does One Add The Digits Of A Large Number?

I have been trying to add the individual digits of a larger number for a while now, and I'm having some trouble. I was wondering if anyone could help me. For example, say I have th

Solution 1:

As a more verbose method than sum() Simply get each char in the string, make it a number and add it.

total = 0#Have total number
bigNumber = str(45858383)          #Convert our big number to a stringfor number in bigNumber:           #for each little number in our big number
    total = total + int(number)    #add that little number to our totalprint(total)                       #Print our total

And if you'd like to do only certain spots:

total = 0                           #Have total number
bigNumber = str(123456789)          #Convert our big number to a string
startPlace = 2                      #Start
endPlace = 4                        #End
for i in xrange(startPlace,endPlace):    #have i keep track of where we are, between start and end
    total = total + int(bigNumber[i])    #Get that one spot, and add it to the total
print(total)                       #Print our total

Solution 2:

Treat it as a string, and sum the individual numbers. Slice if you need to.

sum(map(int,str(12345)))
Out[183]: 15sum(map(int,str(12345)[1:3]))
Out[184]: 5

Solution 3:

one more alternative is to use build in list([iterable]) function

bigNumber = '23455869654325768906857463553522367235'
print sum(int(x)for x in list(bigNumber))
print sum(int(x)for x in list(bigNumber)[5:11])

Post a Comment for "How Does One Add The Digits Of A Large Number?"