trailingZeroes

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

给一个数字n,返回它n!数字后面有多少个0。

public class Solution {
    public int trailingZeroes(int n) {
        int count=0;
        while(n/5>=1)
        {
            count+=n/5;
            n/=5;
        }
        return count;
    }
}
时间: 2024-12-19 20:36:28

trailingZeroes的相关文章

172. Factorial Trailing Zeroes

1. 问题描述 Given an integer n, return the number of trailing zeroes in n!.Note: Your solution should be in logarithmic time complexity.Tags: MathSimilar Problems: (H) Number of Digit One 2. 解题思路 分解质因子, 当且仅当 因子中出现 一对 (2,5)时, 最后结果会增加一个 trailing zero.1. 2的

[LeetCode] Factorial Trailing Zeroes 阶乘末尾0

Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity. Credits:Special thanks to @ts for adding this problem and creating all test cases. Hide Tags Math 这题应该是2014年年底修改该过测试样本,之前的通过

Java-Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity. Credits: Special thanks to @ts for adding this problem and creating all test cases. 看了半天没看懂题目意思 以为要求n结尾0的个数 搞了半天是要求n!即 n的阶乘结

LeetCode172 Factorial Trailing Zeroes. LeetCode258 Add Digits. LeetCode268 Missing Number

数学题 172. Factorial Trailing Zeroes Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity. (Easy) 分析:求n的阶乘中末位0的个数,也就是求n!中因数5的个数(2比5多),简单思路是遍历一遍,对于每个数,以此除以5求其因数5的个数,但会超时. 考虑到一个数n比他小

C 数组模拟阶乘运算

#include <stdio.h> void rdump(int arr[],int len) { int i = 0; for(i=len-1;i >= 0; --i) { printf("%d",arr[i]); } printf("\n"); } void trailingZeroes(int n) { int arr[10000] = {1},len = 1,i = 0,j = 0,c = 0,d = 0; for(i=2; i <

n阶乘 尾数0的个数

class Solution {public: int trailingZeroes(int n) {            if(n<=0) return 0; int i=0;           int res=0; while(n){ res+=n/5; n=n/5; } return res;}}; 很神奇的,eg  125 125=25*5,相当于前前面有1,2,3,4,5,……,20,21,22,23,24,25  * 5 125/5 = 25 相当于前面变成0,0,0,0,1,…

LeetCode Factorial Trailing Zeroes (阶乘后缀零)

题意:如标题 思路:其他文章已经写过,参考其他. 1 class Solution { 2 public: 3 int trailingZeroes(int n) { 4 return n/5<5? n/5: n/5+trailingZeroes(n/5); 5 } 6 }; AC代码

[LeetCode]172.Factorial Trailing Zeroes

题目 Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity. 分析 朴素解法: 首先求出n!,然后计算末尾0的个数.(重复÷10,直到余数非0) 该解法在输入的数字稍大时就会导致阶乘得数溢出,不足取. O(logn)解法: 考虑n!的质数因子. 后缀0总是由质因子2和质因子5相乘得来的.如果我们可以计数

Leetcode: Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity. 解析: 只有2和5相乘才会出现0,其中整十也可以看做是2和5相乘的结果,所以,可以在n之前看看有多少个2以及多少个5就行了,又发现2的数量一定多于5的个数,于是我们只看n前面有多少个5就行了,于是n/5就得到了5的个数,还有一点要注意的就是25这种