Python3 Recursivley Sum Digits of an Integer

北城余情 提交于 2019-12-23 17:18:42

问题


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 function must be left as is. I will include a template below:

def sumdigits(value): 
    #recursively sum digits 

def main():
    number=int(input(“Enter a number :  ”))
    print(sumdigits(number))

main()

Thank you


回答1:


A very short version:

def sumdigits(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.



来源:https://stackoverflow.com/questions/13274207/python3-recursivley-sum-digits-of-an-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!