数字和,Python [英] Digital sum, Python

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

问题描述

我需要写一个代码来计算一个数字的数字之和,这些是问题的确切文本:数字n的数字和是它的数字之和.编写一个递归函数 digitalSum(n),它接受一个正整数 n 并返回它的数字和.例如,digitalSum(2019) 应该返回 12,因为 2+0+1+9=12.这是我写的代码:

I need to write a code that counts the sum of the digits of a number, these is the exact text of the problem:The digital sum of a number n is the sum of its digits. Write a recursive function digitalSum(n) that takes a positive integer n and returns its digital sum. For example, digitalSum(2019) should return 12 because 2+0+1+9=12. These is the code I wrote :

def digitalSum(n):
   L=[] 
   if n < 10:
      return n
   else:
      S=str(n)
      for i in S:
         L.append(int(i))
      return sum(L)

这些代码工作正常,但它不是递归函数,我不允许将任何 int 更改为 str.你能帮我吗?

These code works fine, but it's not a recursive function, and I'm not allowed to change any int to str. May you help me?

推荐答案

试试这个:

def digitalSum(n):
    if n < 10 :
        return n
    return n % 10 + digitalSum( n // 10 )

该算法背后的逻辑是,对于递归函数的每次调用,我们都会砍掉数字的最后一位数字并将其添加到总和中.首先,我们使用 n % 10 获取最后一位数字,然后再次调用该函数,传递最后一位数字被截断的数字:n//10.我们只有在达到一位数时才会停止.在我们停止之后,随着递归调用的返回,数字的总和以相反的顺序计算.

The logic behind this algorithm is that for every call of the recursive function, we chop off the number's last digit and add it to the sum. First we obtain the last digit with n % 10 and then we call the function again, passing the number with the last digit truncated: n // 10. We only stop when we reach a one-digit number. After we stop, the sum of the digits is computed in reverse order, as the recursive calls return.

数字 12345 的示例:

Example for the number 12345 :

5 + digitalSum( 1234 )
5 + 4 + digitalSum( 123 )
5 + 4 + 3 + digitalSum( 12 )
5 + 4 + 3 + 2 + 1 <- done recursing
5 + 4 + 3 + 3
5 + 4 + 6
5 + 10
15

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

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