(javase)使用递归与不使用递归计算N的阶乘

2021/9/19 12:05:05

本文主要是介绍(javase)使用递归与不使用递归计算N的阶乘,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

/*    先不使用递归,计算N的阶乘
    5的阶乘:
      5 * 4 * 3 * 2 * 1
*/
/*
public class RecursionTest04
{
    public static void main(String[] args) 
    {
        int n = 5;
        int retValue = method(n);
        System.out.println(retValue);//120
    }
    public static int method(int n){
        int result = 1;
        for(int i=n;i>0;i--){
            result *= i;
        }
        return result;
    }
}*/

//递归方式
//必须记住,面试题出现的几率很高。
public class RecursionTest04
{
    public static void main(String[] args) 
    {
        int n = 5;
        int retValue = method(n);
        System.out.println(retValue);//120
    }
    public static int method(int n){
        if(n == 1){
            return 1;
        
        }
        return n * method(n - 1);
    }
}
//4 + 3 + 2 + 1
//4 * 3 * 2 * 1
 



这篇关于(javase)使用递归与不使用递归计算N的阶乘的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程