题目及测试
package pid172;
/*阶乘后的零
给定一个整数 n,返回 n! 结果尾数中零的数量。
示例 1:
输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。
示例 2:
输入: 5
输出: 1
解释: 5! = 120, 尾数中有 1 个零.
说明: 你算法的时间复杂度应为 O(log n) 。
*/
public class main {
public static void main(String[] args) {
int[] testTable = new int[]{3,5,7,20};
for (int ito : testTable) {
test(ito);
}
}
private static void test(int ito) {
Solution solution = new Solution();
int rtn;
long begin = System.currentTimeMillis();
System.out.print("ito="+ito+" ");
System.out.println();
//开始时打印数组
rtn = solution.trailingZeroes(ito);//执行程序
long end = System.currentTimeMillis();
//System.out.println(ito + ": rtn=" + rtn);
System.out.println( " rtn=" +rtn);
// for (int i = 0; i < ito.length; i++) {
// System.out.print(ito[i]+" ");
// }//打印结果几数组
System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}
}
解法1(成功,1ms,很快)
0=2*5
而阶乘中,有5必有2,所有只要算有几个5就行了
=n/5+n/25+...
还需要得到每个数分解质因子后5的个数
package pid172;
import java.math.BigInteger;
class Solution {
public int trailingZeroes(int n) {
if(n<=4){
return 0;
}
int now=n/5;
int sum=0;
while(now>0){
sum=sum+now;
now=now/5;
}
return sum;
}
}