Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Trailing zeros of n! | |
* | |
* take care Integer OverFlow | |
* Reference: | |
* http://www.purplemath.com/modules/factzero.htm | |
* http://www.cnblogs.com/EdwardLiu/p/4207498.html | |
*/ | |
public class TrailingZeroes { | |
public static int trailingZeroes(int n) { | |
if (n < 0) { | |
n = -1* n; | |
} | |
int result = 0; | |
for (int i = 5; n / i >= 1; n = n / 5) { | |
result += n / i; | |
} | |
return result; | |
} | |
public static void main(String[] args) { | |
System.out.println(trailingZeroes(1808548329)); | |
} | |
} |
No comments:
Post a Comment