We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I think using tail recursion will be good choice as it reduces the number of call stack. Below code does not require more than one call stack as result of calculated value is passed along with recursion call. Hence there is no wait for any call stack.
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int result = factorial(n, 1);
System.out.println(result);
}
private static int factorial(int n, int currVal){
if(n == 0 || n == 1){
return currVal;
}
return factorial(n-1, n * currVal);
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 9: Recursion 3
You are viewing a single comment's thread. Return to all comments →
I think using tail recursion will be good choice as it reduces the number of call stack. Below code does not require more than one call stack as result of calculated value is passed along with recursion call. Hence there is no wait for any call stack.
public class Solution {