172. 阶乘后的零

 

172. 阶乘后的零_第1张图片


 蠢方法,会越届

class Solution {
public:
    int trailingZeroes(int n) {
        long long record=1;
        int count=0;
        
        /*while(n--)
        {
            record*=n;//n最后一次进来循环是0,所以record,最后值为0
        }*/
        for(int i=n;i>0;i--)
            record*=i;
        while(record%10==0)
        {
            count++;
            record/=10;

        }
        return count;


    }
};

class Solution {
public:
    int trailingZeroes(int n) {
        
        int count=0;
        //阶乘,有多少对2*5 结果的结尾就有多少个0;阶乘中2的个数一定比5多,所以只要求出阶乘式中能有多少个5相乘,即可
        // 1 2 3 4 5 6 7...2*5 ... 3*5... 4*5 ...5*5.....5*5*5
        // 每隔5个数有一个5,每隔25个数有2个5,每个125,有3个5   
        //第一次循环得到被5整除的个数,第二个循环得到被25整除的个数,第三次循环得到被125整除的个数。。。
        //当然能被5整除的个数中,包含了能被25,50...125,中的1个5,再除一次就能得到能被25整除的个数,依此类推
        while(n/5)
        {
            count+=n/5;
            n/=5;
        }
        return count;


    }
};

 

你可能感兴趣的:(算法题)