首页 > 解决方案 > 如何将简单方法转换为递归方法?

问题描述

我创建了这段代码,它根据头部和腿的数量来查找动物的数量


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;
    }

}

但我对递归有点生疏。

标签: javarecursion

解决方案


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);
}

推荐阅读