整数的 Python3 递归求和数字 [英] Python3 Recursivley Sum Digits of an Integer

查看:73
本文介绍了整数的 Python3 递归求和数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助实现一个函数,该函数将取整数的数字并将它们相加.只要 sumDigits 函数实现了递归,就是有效的,main 函数必须保持原样.我将在下面包含一个模板:

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()

谢谢

推荐答案

一个非常简短的版本:

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

value 和 部分使它返回零而不是在超过最后一位时无限递归.

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

value % 10 部分获取最后一位数字(个"位).

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

sumdigits(value//10) 得到除最后一位以外的所有数字之和

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.

这篇关于整数的 Python3 递归求和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆