I'm trying to create a recursive function that adds all the digits in a number. Here's what I've come up with:
def sumOfDigits(num):
num=str(num)
if len(num)==0:
return 0
elif len(num)==1:
return int(num)
elif len(num)>1:
return int(num[0]) + int(num[-1]) + int(sumOfDigits(num[1:-1]))
this seems to work for almost any number:
sumOfDigits(999999999)
>>>81
sumOfDigits(1234)
>>>10
sumOfDigits(111)
>>>3
sumOfDigits(1)
>>>1
sumOfDigits(0)
>>>0
strange things happen though if the number begins with '0'
sumOfDigits(012)
>>>1
sumOfDigits(0123)
>>>11
sumOfDigits(00010)
>>>8
what am I missing here??