Sum the digits of a number

后端 未结 18 1996
抹茶落季
抹茶落季 2020-11-22 10:52

If I want to find the sum of the digits of a number, i.e.:

  • Input: 932
  • Output: 14, which is (9 + 3 + 2)
18条回答
  •  悲哀的现实
    2020-11-22 11:25

    reduce(op.add,map(int,list(str(number))))
    

    Test:

    from datetime import datetime
    number=49263985629356279356927356923569976549123548126856926293658923658923658923658972365297865987236523786598236592386592386589236592365293865923876592385623987659238756239875692387659238756239875692856239856238563286598237592875498259826592356923659283756982375692835692385653418923564912354687123548712354827354827354823548723548235482735482354827354823548235482354823548235482735482735482735482354823548235489235648293548235492185348235481235482354823548235482354823548235482354823548234
    
    
    
    startTime = datetime.now()
    
    for _ in  range(0,100000) :
        out=reduce(op.add,map(int,list(str(number))))
    
    now=datetime.now()
    runningTime=(now - startTime)
    
    print ("Running time:%s" % runningTime)
    print(out)
    

    Running time:0:00:13.122560 2462

提交回复
热议问题