簡體   English   中英

在 python 中查找數字的總和直到總和變為單個數字

[英]Finding sum of digits of a number until sum becomes single digit in python

我正在編寫一個程序,將數字中的數字相加,直到數字中只有一個數字。 例如:

輸入:92
9 + 2 = 11
1 + 1 = 2
Output:2

我當前的代碼:

number = int(input())
total_sum = 0
step = 1
condition = True
while condition:
    while number:
        total_sum += number%10
        number //= 10
    print("Step-%d Sum: %d" %(step, total_sum))
    number = total_sum
    total_sum = 0
    step += 1
    condition = number > 9

一個遞歸實現,它使用記憶化來加快速度:

from functools import cache

@cache
def f(n):
    sum_n = sum(map(int, str(n)))
    if sum_n > 9:
        return f(sum_n)
    return sum_n

print(f(92))
print(f(138))

生產

2
3

這有幫助嗎:

def func(i):
    while True:
        r = 0
        while i > 0:
            r += i % 10
            i //= 10
        if r < 10:
            break
        i = r
    return r

print(func(92))

Output:

2
def sum_end(numb) :
    sum=0
    while numb>0 :
        rem=numb%10
        sum+=rem
        numb=numb//10
    if sum>9 :
        sum=sum_end(sum)
    return sum

print(sum_end(99999999999))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM