146k views
1 vote
Write a recursive method named digitSum that accepts an integer as a parameter and returns the sum of its digits. For example, calling digitSum(1729) should return 1 7 2 9, which is 19. If the number is negative, return the negation of the value. For example, calling digitSum(-1729) should return -19.

1 Answer

1 vote

Answer:

The function in Python is as follows:

def digitSum( n ):

if n == 0:

return 0

if n>0:

return (n % 10 + digitSum(int(n / 10)))

else:

return -1 * (abs(n) % 10 + digitSum(int(abs(n) / 10)))

Step-by-step explanation:

This defines the method

def digitSum( n ):

This returns 0 if the number is 0

if n == 0:

return 0

If the number is greater than 0, this recursively sum up the digits

if n>0:

return (n % 10 + digitSum(int(n / 10)))

If the number is lesser than 0, this recursively sum up the absolute value of the digits (i.e. the positive equivalent). The result is then negated

else:

return -1 * (abs(n) % 10 + digitSum(int(abs(n) / 10)))

User Justin Tilson
by
6.9k points