LeetCode-Factorial Trailing Zeroes

Description:
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.

题意:计算一个非负数的阶乘,其尾部有多少个零;

解法一(超时):很自然的想到算计算出这个数的阶乘,再判断其尾部零的个数;但是,即使用long long也存储不下那么大的数字,因此,考虑用数组来存储计算结果;最后时间复杂度也是太高,因此会导致超时;

Java
class Solution {
    public int trailingZeroes(int n) {
        int[] fac = new int[100000]; //计算阶乘后每一位的数字
        fac[0] = 1;
        int index = 1; //计算阶乘后的位数
        int result = 0; //数字尾部0的个数
        for (int i = 2; i <= n; i++) {
            int carry = 0;
            for (int j = 0; j < index; j++) {
                int temp = fac[j] * i + carry;
                fac[j] = temp % 10;
                carry = temp / 10;
            }
            while (carry > 0) {
                fac[index] = carry % 10;
                carry /= 10;
                index++;
            }
        }
        for (int i = 0; i < index; i++) {
            if (fac[i] == 0) result++;
            else break;
        }
        return result;
    }
}

解法二:这道题的目的不在于要求解阶乘,而是判断一个数的末尾包含的零的个数,而会产生0的两个基本元素就是5和2;对于2来说这个元素是足够找到的,因此我们需要计算可以有多少个的5;

Java
class Solution {
    public int trailingZeroes(int n) {
        return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值