Given an integer n, return the number of trailing zeroes in n!.code
Example 1:leetcode
Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero.
Example 2:it
Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.io
開始寫了一個方法,結果超時了,以下:方法
public static int trailingZeroes(int n) { int num = 0; int num5 = 0; for (int i=1;i<=n;i++){ int nu = i; while(nu%5==0 && nu >0){ num5++; nu = nu/5; } } return num5; }
改爲如下的方法能夠了:im
public static int trailingZeroes(int n) { int count = 0; while(n > 1){ n /= 5; count += n; } return count; }
題目地址:https://leetcode.com/problems/factorial-trailing-zeroes/static