【LeetCode】172. Factorial Trailing Zeroes
原题链接:https://leetcode.com/problems/factorial-trailing-zeroes/description/
题目要求:
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
想法:
0是由2×5得到的,所以统计n前面2和5的个数即可,又2的个数多余5的个数,所以只需统计5的个数即可。还有一点要注意的就是25这种,5和5相乘的结果,所以,还要看n/5里面有多少个5,也就相当于看n里面有多少个25,还有125,625.。
代码如下:
1 class Solution { 2 public: 3 int trailingZeroes(int n) { 4 int res = 0; 5 while(n) 6 { 7 res += n/5; 8 n /= 5; 9 } 10 return res; 11 } 12 };
还有一种递归写法:
1 class Solution { 2 public: 3 int trailingZeroes(int n) { 4 n /= 5; 5 return !n ? 0 : n+trailingZeroes(n); 6 } 7 };
浙公网安备 33010602011771号