设计一个算法,计算出n阶乘中尾部零的个数
public class Solution { /* * @param n: An integer * @return: An integer, denote the number of trailing zeros in n! */ public long trailingZeros(long n) { // write your code here, try to do it without arithmetic operators. long count = 0; for (long i=0;i<n ;i++ ){ count += n/5; n=n/5; } return count; } }
public class Solution { /* * @param n: An integer * @return: An integer, denote the number of trailing zeros in n! */ public long trailingZeros(long n) { // write your code here, try to do it without arithmetic operators. long count = 0; while (n != 0 ){ count += n/5; n=n/5; } return count; } }
上面的测试代码,比下面的,最终的测试结果少了个1.
下面的是正确的。
上面的i一直都在自增长,而n在自减少。
可能在某个时间点,错过了一位。