首页 > 解决方案 > 使用递归的数字的数字根

问题描述

我正在编写一个递归函数来计算给定数字的数字根:

def digital_root(num):
    sum = 0
    while num > 0:
        sum += num % 10
        num = num // 10

    while sum > 10:
        sum = digital_root(sum)

    return sum

我不确定第二个while是否应该用if语句替换,如果是,为什么?(如果没有,为什么不呢?)

当我尝试两个版本时,返回值是相同的。例如,对于数字10598,它们的输出都是5

标签: pythonnumbersdigits

解决方案


如果它厌倦了人们不接受我的解决方案,请确保接受答案,当它对他们有用时

def digital_root(num):
    #Base case for recursion.
    # recursion always needs a base case
    if len(str(num)) == 1:
        return num
    #Get sum of num by turning it into a string and looping through it, 
    #adding each index one by one
    sum = 0
    for i in str(num):
        sum += int(i)
    #get the digital root of the sum
    return digital_root(sum)


def main():
    print(digital_root(27518))



if __name__ == '__main__':
    main()

给你


推荐阅读