Not sure if the test cases have a flaw or something


  • 0
    G

    The basic idea of this problem is to count the sum of multiples of 5,25,125,625....
    I got two solutions here.
    The first one is the below

    public class Solution {
    public int trailingZeroes(int n) {
        int zeros=0;
        while(n>0){
            zeros+=n/5;
            n/=5;
        }
        return zeros;
    }
    

    This is ACed. However, I feel it is not quite right, because by dividing 5 each time, we are actually losing some precision.

    So here comes the second solution

    public class Solution {
    public int trailingZeroes(int n) {
        int zeros=0;
        int five=5;
        while(n>=five){
            zeros+=n/five;
            five*=5;
            if(five>Integer.MAX_VALUE/5)
                break;
        }
        return zeros;
    }
    

    However, it could only pass 500 out of 502 test cases. But I think this solution is exactly doing the counting of those multiples.

    Not sure if I am wrong or there are some problem in the test cases. Any help will be greatly appreciated!


  • 1

    Your five>Integer.MAX_VALUE/5 tests whether it's (un)safe to multiply by 5. You should do it before multiplying by 5. Otherwise you stop one power too early.

    And the repeated division by 5 of the first solution is absolutely correct. Just think of n written in base 5. You're extracting its base-5 digits, and "losing some precision" is just throwing away the digits that you already handled.


  • 0
    G

    Thank you Stefan. I now understand both of them:)


Log in to reply
 

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