简体   繁体   English

用递归查找最后一位数字总和

[英]Finding the last digits sum with recursion

I'm attempting to create a function that will sum all the digits我正在尝试创建一个对所有数字求和的函数
and will return the sum of the summarized number.并将返回汇总数字的总和。

Example:例子:
For Input getNumValue(1589)对于输入getNumValue(1589)
The Output will be: 5输出将是:5
Becuase: 1 + 5 + 8 + 9 = 23因为:1 + 5 + 8 + 9 = 23
And 2 + 3 = 5 2 + 3 = 5
So the output will be 5所以输出将是 5
Because we can't split it into more digits.因为我们不能把它分成更多的数字。

I did managed to create a recursion function that summarize the digits:我确实设法创建了一个总结数字的递归函数:

def getNumValue(number: int):
    if number == 0:
        return 0
    return (number % 10 + getNumValue(int(number / 10)))

But I can't seem to utilize it to my cause.但我似乎无法将它用于我的事业。

Btw顺便提一句
I don't want to use any strings我不想使用任何字符串
And I'm trying to use recursion so far no luck.到目前为止,我正在尝试使用递归,但没有运气。
I bet this is a known mathematic problem I'm just unfamiliar with.我敢打赌,这是一个我不熟悉的已知数学问题。
Any advice?有什么建议吗?

Even shorter:更短:

def getNumValue(number: int): return ((number-1) % 9) + 1

The digit sum is always in the same remainder class mod 9 as the original decimal number, this applies recursively, and thus reducing it to one digit just is the remainder under division by 9.数字和总是与原始十进制数处于相同的余数类 mod 9 中,这递归适用,因此将其减少到一位就是除以 9 的余数。

The shift by 1 just serves the purpose that the remainder class 0 is represented by 9 .移位1只是为了将余数类09表示。

you can make a final check before returning the answer.您可以在返回答案之前进行最后检查。

def getNumValue(number: int):
    if number == 0:
        return 0
    answer = (number % 10 + getNumValue(int(number // 10)))
    if answer < 10:
        return answer
    return getNumValue(answer)


print(getNumValue(15899999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999))

OUTPUT :输出 :

9

You can check if number is greater than 9. If yes, then call the function again:您可以检查数字是否大于 9。如果是,则再次调用该函数:

def getNumValue(number: int):
    if number == 0:
        return 0
    j=(number % 10 + getNumValue(int(number // 10)))
    if j>9:
        return getNumValue(j)
    return j
print(getNumValue(getNumValue(1589)))

Without recursion:没有递归:

def getNumValue(number: int) -> int:
    while True:
        total = 0
        while number:
            total += number % 10
            number //= 10
        number = total
        if total <= 9:
            return total
>>> getNumValue(number)
5

pythonic recursion :) pythonic递归:)

def getNumValue(number=1589):
    ans = number % 10 + getNumValue(int(number / 10)) if number else 0
    return getNumValue(ans) if ans > 10 else ans

output输出

5

With two lines of code用两行代码

getNumValue = lambda x: 0 if x == 0 else x % 10 + getNumValue(int(x / 10))
output = getNumValue(getNumValue(1589))
print(output)
//5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM