LeetCode 172. Factorial Trailing Zeroes

  • 2020 年 2 月 14 日
  • 笔记

题目

题意:问你一个数的阶乘,末尾有多少0

题解:一个数的阶乘结果的末尾的0,根据分解质因数,只能是25得到的,所以把这个数的阶乘分解质因数,看有多少个25,2显然是比5多的,所以数一数有多少个5就可以了。

比如24的阶乘里分解质因数有几个五呢?5 里有一个5,10,15,20里各有一个,一共4=24/5 个五。但是25 可以分解为5*5,所以25的阶乘里分解质因数有4+2=6个五,

但是到了125,125有三个五,所以一个数n的阶乘里有多少个五呢?

x = n/5 + n/25 + n/125 …..

class Solution {  public:      int trailingZeroes(int n) {            long long int x=5;          int ans=0;          while(x<=n)          {              ans+=n/x;              x*=5;          }            return ans;        }  };