I'm solving LeetCode #172:
Given an integer n, return the number of trailing zeroes in n!
Constraints:
0 <= n <= 104
My code finds the answer of n! first and then counts the number of trailing zeroes. However, running the code throws a stack overflow exception, and I can't for the life of me figure out why.
This is the code:
class Solution {
public int trailingZeroes(int n){
int fact = findFactorial(n); // 120
int ans = 0;
// how many zeroes does fact have?
String ansString = Integer.toString(fact);
// edge - if string is only one character long
if (ansString.length()==1) {
return 0;
}
// loop from the end counting the continuous zeroes
for (int i= ansString.length()-1 ; i > 0; i--){
Character cha = ansString.charAt(i);
if (cha.equals('0')) {
ans++;
}
else {
break;
}
}
return ans;
}
public int findFactorial(int n){
// base case
if (n==1) return 1;
// reduct towards base case
else {
int f = n * findFactorial(n-1);
return f;
}
}
}