作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是一道让我和我的同学都难过的过去考试的题目:
Use recursion to multiply together every number in a series without using local variables. Assume:
- the parameters are positive
- the first parameter is less than the second parameter
- the result is less than 231
例如,rangeProduct(1, 5)
应该返回 120
,因为 1x2x3x4x5 是 120
使用这个方法签名:
public static int rangeProduct(int valueOne, int valueTwo) {
return ?;
}
如果有人知道如何做到这一点,那只是为了让我的学习受益,如果您正在寻找一些练习,或者只是对一个饥肠辘辘、知识一般的计算机科学专业的学生表示同情,那就试试吧!
最佳答案
试试这个:
public static int rangeProduct(int valueOne, int valueTwo) {
if(valueOne>=valueTwo)
return valueOne;
return rangeProduct(valueOne, valueTwo-1) * valueTwo;
}
按照您指定的确切顺序执行计算:
1x2=2, 2x3=6, 6x4=24, 24x5=120
关于java - 使用递归来乘以没有局部变量的数字序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43373099/
我是一名优秀的程序员,十分优秀!