Skip to content Skip to sidebar Skip to footer

Python3 Recursivley Sum Digits Of An Integer

I need help implementing a function that will take the digits of an integer and sum them together. As long as the sumDigits function implements recursion, it is valid, and the main

Solution 1:

A very short version:

defsumdigits(value):
    return value and (value % 10 + sumdigits(value // 10))

The value and part makes it return zero rather than recurse infinitely once it gets past the last digit.

The value % 10 part gets the last digit (the "ones" place).

The sumdigits(value // 10) gets the sum of all of the digits except the last digit

// is integer division, throwing away the fractional part of the result for you automatically.

Post a Comment for "Python3 Recursivley Sum Digits Of An Integer"