Counting trailing zeros of numbers resulted from factorial

后端 未结 10 1721
北荒
北荒 2020-11-30 07:48

I\'m trying to count trailing zeros of numbers that are resulted from factorials (meaning that the numbers get quite large). Following code takes a number, compute the facto

10条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 08:48

    The best with logarithmic time complexity is the following:

    public int trailingZeroes(int n) {
        if (n < 0)
            return -1;
    
        int count = 0;
        for (long i = 5; n / i >= 1; i *= 5) {
            count += n / i;
        }
    
        return count;
    }
    

    shamelessly copied from http://www.programcreek.com/2014/04/leetcode-factorial-trailing-zeroes-java/

提交回复
热议问题