How does one add the digits of a large number?

前端 未结 3 1777
你的背包
你的背包 2021-01-27 18:12

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, s

相关标签:
3条回答
  • 2021-01-27 18:45

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

    sum(map(int,str(12345)))
    Out[183]: 15
    
    sum(map(int,str(12345)[1:3]))
    Out[184]: 5
    
    0 讨论(0)
  • 2021-01-27 18:53

    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 string
    for number in bigNumber:           #for each little number in our big number
        total = total + int(number)    #add that little number to our total
    print(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
    
    0 讨论(0)
  • 2021-01-27 19:05

    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])
    
    0 讨论(0)
提交回复
热议问题