首页 > 解决方案 > 简单递归到迭代

问题描述

我认为我的解决方案太复杂了,我该如何简化它?

问题:

public static int calc (int g, int h) {
    if (h > 5) {
        g += h;
        return calc (g, h − 2) ∗ 2;
    } else {
        return g;
    }
}

我的解决方案:

public static int calc (int g, int h) {
    int counter = 0;
    for (; h > 5; h -= 2){
        g += h;
        counter++;
    }
    return g * (int) Math.pow(2, counter);
}  

标签: javarecursioniteration

解决方案


I'd be more inclined to simplify your original recursive code:

public static int calc(int g, int h) {
    if (h <= 5) {
        return g;
    }

    return 2 * calc(g + h, h - 2);
}

But if I were to simplify your iterative code, I'd try to avoid introducing the floating point Math.pow() and keep the whole operation int:

public static int calc(int g, int h) {
    int power;

    for (power = 1; h > 5; h -= 2) {
        g += h;
        power *= 2;
    }

    return g * power;
}

推荐阅读