zoukankan      html  css  js  c++  java
  • LintCode #2 尾部的零

    计算阶乘尾部的0的个数,初一看很简单。

    先上代码

    public static long GetFactorial(long n)
            {
                if (n == 0 || n == 1)
                    return 1;
    
                return n*GetFactorial(n - 1);
            }
    
    
    //Main方法中调用
    
                var result = GetFactorial(11);
    
                int num = 10;
                int count = 0;
                while (true)
                {
                    if (result % num == 0)
                    {
                        num = num * 10;
                        count++;
                    }
                    else
                    {
                        break;
                    }
                }
    //count就是最终的结果

    提交以后才发现问题,计算阶乘的数太大,会导致溢出。查了会资料,用数组存储数字,就不会有溢出的问题了。比如数字120, 存在数组里的结果是 a[0]=0, a[1]=2, a[2]=1

    public static List<int> GetFactorial(int n)
            {
                List<int> r = new List<int>()
                {
                    1
                };
    
                if (n == 0 || n == 1)
                    return r;
    
                int num = 0;
    
                for (int j = 1; j <= n; j++)
                {
                    for (int i = 0; i < r.Count; i++)
                    {
                        var tmp = r[i] * j + num;
                        if (tmp > 9)
                        {
                            r[i] = tmp % 10;
                            num = tmp / 10;
                        }
                        else
                        {
                            r[i] = tmp;
                            num = 0;
                        }
                    }
    
                    if (num > 0)
                    {
                        r.Add(num);
                        num = 0;
                    }
                }
    
                return r;
            }
    
    //Main方法中调用, count就是最终的结果
    var list = GetFactorial(105);
    
                int count = 0;
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i] == 0)
                    {
                        count++;
                    }
                    else
                    {
                        break;
                    }
                }

     计算105或者在大一点的数据的阶乘没有问题,不过在提交的时候有又情况了。

    LintCode给出的测试数据是1001171717的阶乘,期望结果是250292920。提示错误为:Memory Limit Exceeded。一定是在用数组存储阶乘结果的时候,内存超限了。

    运行了一下,想看看这个数的阶乘是多少,结果运行了好长时间还没有算完,还需要进行优化,考虑中...

  • 相关阅读:
    基于应用外壳的架构
    示例代码和环境配置
    获取元素位置信息:getBoundingClientRect
    nodejs学习记录
    网页整理 --- 要换工作了,把这一堆网页先存起来
    删除网页上的广告
    周数的处理
    十六进制
    [例]字体改变,文章位置不变
    haslayout和BFC
  • 原文地址:https://www.cnblogs.com/icebutterfly/p/8892143.html
Copyright © 2011-2022 走看看