1. 程式人生 > >LeetCode刷題EASY篇Factorial Trailing Zeroes

LeetCode刷題EASY篇Factorial Trailing Zeroes

題目

Given an integer n, return the number of trailing zeroes in n!.

Example 1:

Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.

Note: Your solution should be in logarithmic time complexity.

 

我的解法

利用遞迴求階乘,然後利用求mod運算,看到每個位數是否為0,為0則計數,返回計數結果。

程式碼邏輯沒有問題,但是數字較大的情況下會stackoverflow,所示修改為迭代試試。

 

遞迴方法:

class Solution {
    
    
    private int caculate(int n){
        if(n<=0){
            return 0;
        }
        if(n==1){
            return 1;
        }
        return n*caculate(n-1);
    }
    
    public int trailingZeroes(int n) {
        int res=caculate(n);
        int count=0;
        while(res>0){
            int modRes=res%10;
            if(modRes==0){
                count++;
            }
            res=res/10;
        }
        return count;
        
    }
}

非遞迴方法

class Solution {
    
    
    private int caculate(int n){
        int res=1;
        for(int i=1;i<=n;i++){
            res=res*i;
        }
        return res;
    }
    
    public int trailingZeroes(int n) {
        int res=caculate(n);
        int count=0;
        while(res>0){
            int modRes=res%10;
            if(modRes==0){
                count++;
            }
            else{
                break;
            }
            res=res/10;
        }
        return count;
        
    }
}

邏輯沒有問題,但是結果不對,發現階乘的結果int儲存範圍不夠,所以改成long後13的階乘正確了。但是30的階乘又不對了,因為long也儲存不下所有數的階乘,終究會出現問題的。

class Solution {
    
    
    private int caculate(int n){
        int res=1;
        for(int i=1;i<=n;i++){
            res=res*i;
        }
        return res;
    }
    
    public int trailingZeroes(int n) {
        int res=caculate(n);
        int count=0;
        while(res>0){
            int modRes=res%10;
            if(modRes==0){
                count++;
            }
            else{
                break;
            }
            res=res/10;
        }
        return count;
        
    }
}

正確解法

題目要求log時間複雜度,所以,我的解法其實不滿足,正確解法,很簡單,一句話,

計算n中有多少個5

 

class Solution {
    
    
    public int trailingZeroes(int n) {
       if(n==0) return 0;
        return n/5+trailingZeroes(n/5);
        
    }
}