要求末尾有多少个零,则该数应为 $x\times 10^k$ 的形式等于 $x\times (2^k\times 5^k)$ 在阶乘里,2 的数量远大于 5,所以我们只用统计有多少个 5 就行,对于一个数的阶乘,例如 6,1*2*3*4*5*6 = 1*2*3*2*2*5*6,因数中有一个 5,所以答案就是 1
- class Solution {
- public int trailingZeroes(int n) {
- int ans = 0;
- while(n > 0) {
- ans += n / 5;
- n /= 5;
- }
- return ans;
- }
- }