【发布时间】:2014-06-10 08:47:51
【问题描述】:
给定两个数字,比如说 (14, 18),问题是递归地找到这个范围内所有数字的总和,14,15,16,17,18。现在,我已经使用循环来完成此操作,但递归执行此操作时遇到了麻烦。
这是我的递归解决方案:
def sum_cumulative_recursive(a,b)
total = 0
#base case is a == b, the stopping condition
if a - b == 0
puts "sum is: "
return total + a
end
if b - a == 0
puts "sum is: "
return total + b
end
#case 1: a > b, start from b, and increment recursively
if a > b
until b > a
puts "case 1"
total = b + sum_cumulative_recursive(a, b+1)
return total
end
end
#case 2: a < b, start from a, and increment recursively
if a < b
until a > b
puts "case 2"
total = a + sum_cumulative_recursive(a+1, b)
return total
end
end
end
以下是一些示例测试用例:
puts first.sum_cumulative_recursive(4, 2)
puts first.sum_cumulative_recursive(14, 18)
puts first.sum_cumulative_recursive(-2,-2)
我的解决方案适用于 a > b 和 a
如何修复此代码以使其正常工作?
感谢您的宝贵时间。
【问题讨论】:
-
听起来像是功课。它闻起来像家庭作业。是作业吗,宝贝?咕噜,咕噜。
-
a==b时应该是什么结果? -
不,这是一个实习职位的面试问题。
-
return a+b + result(a+1,b) 并包含一个情况,如果 a==b 返回 0,那么它将级联初始调用,您将得到一个结果
-
递归?哇,我本来想说
(14..18).reduce(:+)。 ;-)