Java time limit too short?


  • 0
    C

    The following Java code exceeds the time limit:

    public class Solution {
        public int trailingZeroes(int n) {
            int result = 0;
            int k = 5;
            while (k <= n) {
                result += n / k;
                k *= 5;
            }
    
            return result;
        }
    }

  • 12
    R

    when you multiply K with 5 at some point it will cross the value Integer.Max_value and at that time K become negative , So in such a case while loop will become an infinite loop. there you need some modification in your programe:

     public int trailingZeroes(int n) {
        if(n<5)
        return 0;
        
        int x =5;
        int zero =0;
        while(x <= n/5){
            zero += n/x;
            x = x*5;
        }
         zero += n/x;
        return zero;
    }

  • 0
    C

    Thank you very much.


Log in to reply
 

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