Simple Java Recursive Solution and Explanation


  • 0
    M
    public int trailingZeroes(int n) {
            
            /**
             * Why this logic ??
             * Because number of 0s are determined by (5 x 2) products.
             * Given any number n, there will always be a greater number of 2s than 5s as its multiples.
             * So we need to count only the total 5s that are multiples/exactdivisors of a number.
             * and then recurse on n/5.
             **/
            
            if (n == 0) {
                return 0;
            }
            
            return n/5 + trailingZeroes(n/5);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.