zoukankan      html  css  js  c++  java
  • LeetCode【172. 阶乘后的零】

    最开始一看,就觉得挺简单,就是先算出阶乘的值,再除以10,如果%为0,count++,然后s=s/10,如果不为0,就直接输出。

    class Solution {
        public int trailingZeroes(int n) {
            int i;
            int s = 1;
            int count = 0;
            for(i = 1;i <= n;i++)
            {
                s = s*i;
            }
            while(s != 0)
            {
                if(s % 10 == 0)
                {
                    count++;
                    s = s / 10;
                }
                else
                {
                    break;
                }
            }
            return count;
        }
    }

    前面都很正常,有问题的就是13以后,因为int型是4个字符,所以超过了就会自动省略后面的值,

    s改为long型时,就是到30以后,有问题,那么,计算出来阶乘值这个思路是有问题的,数值太大了。

    再思考思考10,可以考虑其中有多少个5.

    class Solution {
        public int trailingZeroes(int n) {
            if (n <= 1) {
                return 0;
            }
            int count = 0;
            while (n != 0) {
                count = count + n / 5;
                n = n / 5;
            }
            return count;
        }
    }

    这里之所以n = n/5,因为每隔5个数,应该多了一个5,

    比如30

    应该有30,25,20,15,10,5,其中,25就含有两个5,

    同时,50,45,40,35,30...,50含有两个5,就是每隔5个数,count应该再增加1

    那么在这里n/5就可以判断是否大于5个数。

  • 相关阅读:
    POJ 3672 水题......
    POJ 3279 枚举?
    STL
    241. Different Ways to Add Parentheses
    282. Expression Add Operators
    169. Majority Element
    Weekly Contest 121
    927. Three Equal Parts
    910. Smallest Range II
    921. Minimum Add to Make Parentheses Valid
  • 原文地址:https://www.cnblogs.com/wzwi/p/10888871.html
Copyright © 2011-2022 走看看