Java递归方法,用于对2的幂进行求和,从0到N [英] Java recursive method for summing the powers of 2, from 0 to N

查看:169
本文介绍了Java递归方法,用于对2的幂进行求和,从0到N的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图学习递归(我知道在这种情况下不需要递归)

so im trying to learn recursion (i know in this case recursion is not necessary)

我已经编写了此方法,该方法有效

i have already written this method, which works

public static int method(int number) {
    if(number == 0) {
        return 1;
    }
    else {
        return (int)Math.pow(2,number) + method(number-1);
    }
}

这非常适合将2的幂从0到数字求和,但是我想知道是否有一种方法可以将Math.pow()替换为另一个递归方法

this works perfectly for summing the powers of 2 from 0 to number, but i was wondering if there was a way to replace the Math.pow() with another recursive method call

推荐答案

您可以将其用作递归幂函数:

You can use this as a recursive power function:

public static int powerOf2(int number) {
    if (number == 0) {
        return 1;
    } else {
        return 2 * powerOf2(number - 1);
    }
}

或者,作为单行主体:

return number > 0 ? 2 * powerOf2(number - 1) : 1;

这篇关于Java递归方法,用于对2的幂进行求和,从0到N的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆