【leetcode】172. Factorial Trailing Zeroes

版权声明:来自 T2777 ,请访问 https://blog.csdn.net/T2777 一起交流进步吧 https://blog.csdn.net/T2777/article/details/87548589

题目描述:

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.

问题描述比较简单,给定一个数 n ,求 n ! ,判断 n! 的十进制值末尾有多少个0.

虽然看起来比较简单,然而,只是想当然的先用一个循环求 n!,再通过末尾求余的方法去判断有多少个0,在n取值较大的情况下回出现超时的问题,导致提交无法通过,这里介绍一种比较简单的解法思路:

后缀的 0 总是由 2 和 5 相乘得到的,那么只要判断出 n! 相乘的因子中有多少个配对的 2 和 5 即可,例如 5!,1*2*3*4*5 = 120 ,后缀有 1 个0 ,阶乘因子中有一个5 和 2个 2 的倍数( 2 和 4 ),通过观察发现后缀有 0 的数的值的结果通常因子中 5 的倍数小于2的倍数,那么只要求共有多少个质因子 5 即可(5的倍数看做多个质因子),通过这种方法得到共有多少个质因子 5 即可。

代码:

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

猜你喜欢

转载自blog.csdn.net/T2777/article/details/87548589