zoukankan      html  css  js  c++  java
  • Factorial Trailing Zeroes (Divide-and-Conquer)

    QUESTION

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

    Note: Your solution should be in logarithmic time complexity.

    FIRST TRY

    class Solution {
    public:
        int trailingZeroes(int n) {
            int divident;
            int nOf2 = 0;
            int nOf5 = 0;
            while(n%2 == 0)
            {
                nOf2++;
                divident = n/2;
            }
            while(n%5 == 0)
            {
                nOf5++;
                divident = n/5;
            }
            return min(nOf2,nOf5);
        }
    };

    Result: Time Limit Exceeded

    Last executed input: 0

    SECOND TRY

    考虑n=0的情况

    class Solution {
    public:
        int trailingZeroes(int n) {
            int divident;
            int nOf2 = 0;
            int nOf5 = 0;
            for(int i = 1; i < n; i++)
            {
                divident = i;
                while(divident%2 == 0)
                {
                nOf2++;
                divident /= 2;
                }
                divident = i;
                while(divident%5 == 0)
                {
                nOf5++;
                divident /= 5;
                }
            }
            return min(nOf2,nOf5);
        }
    };

    Result:  Time Limit Exceeded

    Last executed input:1808548329

    THIRD TRY

    2肯定比5多

    要注意的就是25这种,5和5相乘的结果,所以,还要看n/5里面有多少个5,也就相当于看n里面有多少个25,还有125,625...

    class Solution {
    public:
        int trailingZeroes(int n) {
            if(n==0) return 0;
            int divident=n;
            int nOf5 = 0;
    
            while(divident!= 0)
            {
                divident /= 5;
                nOf5+=divident;
            }
    
            return nOf5;
        }
    };

    Result: Accepted

  • 相关阅读:
    nginx设置开机自启
    sublimeText3和phpstrom使用
    快捷键整理
    nginx日志分割及备份
    nginx日志设置
    nginx上部署PHP
    C语言三种参数传递方式
    浮点数在内存中的存储方式
    windows下git安装过程
    偏移二进制编码和二进制补码的区别
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4199843.html
Copyright © 2011-2022 走看看