Shortest concise solution from geeksforgeeks


  • 0
    S
    // http://www.geeksforgeeks.org/count-trailing-zeroes-factorial-number    
    // the result is equal to count total number of 5s in prime factors of n!
    int trailingZeroes(int n) {
        int ans = 0;
        for (int i = 5; n >= i; i *= 5) {
           ans += n / i;
        }
        return ans;
    }

  • 1
    L

    a shorter one

    int trailingZeroes(int n)  {
        int c = 0;
        for( ; n > 4; c += (n/=5) );
        return c;
    }

  • 0
    Q

    Actually, my method is like this, but it's LTE!


  • 0
    S

    You can share your code, and find the LTE reason.


  • 0
    Q
        int res = 0;
        for(int m = 5; m <= n; m *= 5){
            res += n / m;
        }
        return res;

  • 0
    Q

    Last executed input: 2147483647


  • 0
    Q
        int res = 0;
        for(; n > 4; n /= 5){
            res += n / 5;
        }
        return res;
    

    //When I modified the code like this, it passed the OJ, I think maybe we should not use extra varisbles.


  • 0
    C

    When n is really large, m might be overflow to a negative number. Therefore the loop will never exit. This is how you get your TLE


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.