Factorial Trailing Zeroes--LeetCode

你的名字 2022-08-07 13:34 278阅读 0赞

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

Note: Your solution should be in logarithmic time complexity.

思路:对于一个数的阶乘后面有多少个0,一个数 n 的阶乘末尾有多少个 0 取决于从 1 到 n 的各个数的因子中 2 和 5 的个数, 而 2 的个数是远远多余 5 的个数的, 因此求出 5 的个数即可. 题解中给出的求解因子 5 的个数的方法是用 n 不断除以 5, 直到结果为 0, 然后把中间得到的结果累加. 例如, 100/5 = 20, 20/5 = 4, 4/5 = 0, 则 1 到 100 中因子 5 的个数为 (20 + 4 + 0) = 24 个, 即 100 的阶乘末尾有 24 个 0. 其实不断除以 5, 是因为每间隔 5 个数有一个数可以被 5 整除, 然后在这些可被 5 整除的数中, 每间隔 5 个数又有一个可以被 25 整除, 故要再除一次, … 直到结果为 0, 表示没有能继续被 5 整除的数了.

  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5. int trailingZeroes(int n)
  6. {
  7. int count=0;
  8. int num =n,i;
  9. while(num)
  10. {
  11. count += num/5;
  12. num = num/5;
  13. }
  14. return count;
  15. }
  16. int main()
  17. {
  18. cout<<trailingZeroes(100)<<endl;
  19. system("pause");
  20. return 0;
  21. }

发表评论

表情:
评论列表 (有 0 条评论,278人围观)

还没有评论,来说两句吧...

相关阅读