Why my code didn't pass the test?


  • 4
    Z

    The code is quite simple and straight forward:

    int trailingZeroes(int n) {
    int num = 0;

    for(int test=5; test<=n; test*=5)
    {
    	num += n/test;
    }
    
    return num;
    

    }

    However, system test returns:

    Status: Time Limit Exceeded
    Last executed input: 2147483647

    My questions are:

    1. This "last input" is obviously a long int, rather than int. Why does the system care about a long int type since the pre-set class uses an int function?

    2. Why did the recursive function passed system test? What's the difference with my function?

    int trailingZeroes(int n) {
    return n==0 ? 0 : n/5+trailingZeroes(n/5);
    }

    Thanks!


  • 0
    W

    I have just met the same problem.


  • 3
    Z

    test*5 may cause overflow, but it won't happen in recursive function. Try to add if(test>INT_MAX/5) return num;


  • 0
    J

    use

    for(long long  test=5; test<=n; test*=5)
    {
        num += n/test;
    }
    

Log in to reply
 

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