广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C++实现LeetCode(172.求阶乘末尾零的个数)
  • 708
分享到

C++实现LeetCode(172.求阶乘末尾零的个数)

2024-04-02 19:04:59 708人浏览 独家记忆
摘要

[LeetCode] 172. Factorial Trailing Zeroes 求阶乘末尾零的个数 Given an integer n, return the num

[LeetCode] 172. Factorial Trailing Zeroes 求阶乘末尾零的个数

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

Example 1:

Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

这道题并没有什么难度,是让求一个数的阶乘末尾0的个数,也就是要找乘数中 10 的个数,而 10 可分解为2和5,而2的数量又远大于5的数量(比如1到 10 中有2个5,5个2),那么此题即便为找出5的个数。仍需注意的一点就是,像 25,125,这样的不只含有一个5的数字需要考虑进去,参加代码如下:

c++ 解法一:


class Solution {
public:
    int trailingZeroes(int n) {
        int res = 0;
        while (n) {
            res += n / 5;
            n /= 5;
        }
        return res;
    }
};

Java 解法一:


public class Solution {
    public int trailingZeroes(int n) {
        int res = 0;
        while (n > 0) {
            res += n / 5;
            n /= 5;
        }
        return res;
    }
}

这题还有递归的解法,思路和上面完全一样,写法更简洁了,一行搞定碉堡了。

C++ 解法二:


class Solution {
public:
    int trailingZeroes(int n) {
        return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
    }
};

Java 解法二:


public class Solution {
    public int trailingZeroes(int n) {
        return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
    }
}

GitHub 同步地址:

https://github.com/grandyang/leetcode/issues/172

类似题目:

Number of Digit One

Preimage Size of Factorial Zeroes Function    

参考资料:

Https://leetcode.com/problems/factorial-trailing-zeroes/

https://leetcode.com/problems/factorial-trailing-zeroes/discuss/52371/My-one-line-solutions-in-3-languages

https://leetcode.com/problems/factorial-trailing-zeroes/discuss/52373/Simple-CC%2B%2B-Solution-(with-detailed-explaination)

到此这篇关于C++实现LeetCode(172.求阶乘末尾零的个数)的文章就介绍到这了,更多相关C++实现求阶乘末尾零的个数内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: C++实现LeetCode(172.求阶乘末尾零的个数)

本文链接: https://www.lsjlt.com/news/131703.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C++实现LeetCode(172.求阶乘末尾零的个数)
    [LeetCode] 172. Factorial Trailing Zeroes 求阶乘末尾零的个数 Given an integer n, return the num...
    99+
    2022-11-12
  • C++怎么求阶乘末尾零的个数
    本篇内容介绍了“C++怎么求阶乘末尾零的个数”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!求阶乘末尾零的个数C++ 解法一:class&nb...
    99+
    2023-06-20
  • C++实现LeetCode(58.求末尾单词的长度)
    [LeetCode] 58. Length of Last Word 求末尾单词的长度 Given a string s consists of upper/lo...
    99+
    2022-11-12
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作