Recursive Java 2 line solution


  • 0

    The idea is that, if n < 5 then there's no zero, for n = 5, 10, 15, 20 there are 1,2,3,4 zeroes, which are n / 5 + n / 5 / 5 zeroes respectively. The same holds for n = 25, there are n / 5 + n / 5 / 5 = 5 + 1 zeroes.

    public class Solution {
        public int trailingZeroes(int n) {
            if (n < 5) 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.