首页 > 解决方案 > 如何使用递归查找加到 10 的数字

问题描述

我正在尝试编写一个函数,该函数将 int 作为参数并找到其中的数字对数加到 10。

例如,7645238 有 3 对,因为:7 + 3 = 10、6 + 4 = 10 和 2 + 8 = 10。

我必须递归地执行此操作,并且我已经完成了大部分代码,我只是有一个小问题。我在递归函数中使用了循环和计数器变量,但是每次函数循环时计数器变量都会重置。因此,如果一个数字有超过一对加到 10,计数器将始终只返回 1。

这是我在python中的代码:

def findPairs(num):

    count = 0
    num = str(num)

    # base case if length of num is 1
    if len(num) == 1:
        return 0
    # loops through the rest of the number looking for pairs
    else:
        for n in num[1:]:
            if int(num[0]) + int(n) == 10:
                count = count + 1
        findPairs(num[1:])
    return count

任何帮助将不胜感激!

标签: pythonloopsrecursion

解决方案


我认为问题出在返回代码中,您应该返回当前整数的计数器 + 递归计数器总和,所以这段代码可能会解决问题:

def findPairs(num):

count = 0
num = str(num)

# base case if length of num is 1
if len(num) == 1:
    return 0
# loops through the rest of the number looking for pairs
for n in num[1:]:
     if int(num[0]) + int(n) == 10:
         count = count + 1
return count + findPairs(num[1:])

推荐阅读