Factorial using Recursion in Java

前端 未结 18 1445
春和景丽
春和景丽 2020-11-27 13:43

I am learning Java using the book Java: The Complete Reference. Currently I am working on the topic Recursion.

Please Note: There are similar questi

18条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 14:12

    The correct one is :

    int factorial(int n)
    {
        if(n==0||n==1)
            return 1;
        else 
            return n*factorial(n-1);
    }
    

    This would return 1 for factorial 0. Do it believe me . I have learned this the hard way. Just for not keeping the condition for 0 could not clear an interview.

提交回复
热议问题