java - 如何将简单方法转换为递归方法?
问题描述
我创建了这段代码,它根据头部和腿的数量来查找动物的数量
public class howmanyAnimals {
public static void main(String[] args) {
int Heads = 100;
int legs = 300;
int animals = animalHeads(Heads, legs);
System.out.println("Number of cows: " + animals);
System.out.println("Number of chickens: "+ (Heads - animals));
}
static int animalHeads(int heads, int legs) {
int count = 0;
count = (legs) - 2 * (heads);
count = count / 2;
return count;
}
}
输出:
Number of cows: 50
Number of chickens: 50
这很好用,但是方法 animalHeads 需要是 Recurive
我尝试了这种方法
static int animalHeads(int heads, int legs) {
int count = 0;
count = (legs) - 2 * (heads);
count = count / 2;
if (count % 2 == 0) {
return 0;
} else if (count % 2 != 0) {
return count = animalHeads(100, 300);
}
return count;
}
}
但我对递归有点生疏。
解决方案
Well, animalHeads
actually calculates the number of cows.
Since a cow has 1 head and 4 legs, the recursive step should be:
animalHeads(heads, legs) = 1 + aminalHeads(heads - 1, legs - 4);
However, since the heads and legs count include chickens, which have 1 head and 2 legs, the recursion should end when all the remaining heads and legs belong to chickens, which happens when the remaining number of legs is twice the remaining number of heads.
static int animalHeads(int heads, int legs)
{
if (heads * 2 == legs) { // only chickens are left
return 0;
}
return 1 + animalHeads(heads - 1, legs - 4);
}
推荐阅读
- c# - 为什么将所有材料都放入 List 时,所有项目都是 null ?以及如何在淡入/淡出时更改对象位置?
- python - Pytorch NN 错误:预期输入 batch_size (64) 与目标 batch_size (30) 匹配
- mysql - 如何增量计算重复实例的数量
- flutter - 调整颤振大小时列重复
- wordpress - 选择后WordPress图片的颜色会发生变化
- python - 如何在不返回实例的情况下使用方法修改python中类的属性(就地操作)
- python - 在时间范围内查找现值,熊猫
- google-sheets - 如何在谷歌表格中删除这种表格
- nginx - 为 yii 2 设置 nginx
- django - Django Rest Framework - 当获取模型类型的对象不是 JSON 可序列化时,如何从响应中返回模型的所有信息?