在lintcode上 边看到这样一个题,lintcode对于这道题的定义是简单。一点也不简单!上代码:
我自己写的:
public int getCount(int n){ int count=0; long x = 1; for(int i=1;i<=n;i++){ x *=i; } String str = String.valueOf(x); char[] chars=str.toCharArray(); for(int i=chars.length-1;i>=0;i--){ if(chars[i]=='0'){ count++; }else{ break; } } return count; }
我对于这个题的思路就是,将这个阶乘计算出来,然后数零。这种算法,在一定的条件下是对的,但是到某一个值的时候,由于数据类型的不一致,容易数据溢出,这也是这道题最笨的算法了。
于是就在网上继续找寻答案,答案有三种,其中第一种就是我的这种,也是不推荐的一种,计算过程太过复杂。
第二种:
public long getCount(long n){ long count = 0; long pwr = 25;//pwr是5的一次幂 for(long temp = 5;temp <= n;temp +=5){//以5的步长迭代增加 count++; // pwr = 25; while(temp%pwr==0){ count++; pwr *=5;//pwr 是5的次幂 } } return count; }
这种算法,巧妙的分析了,那些数的阶乘末尾有零,通过一些推导之后,就有 这个算法,在我看来,这样的算法已经足够满足的时候,网上继续说,这个效率太低了。what,于是出现了第三种算法:
public long getCount(long n){ long count = 0; long temp = n / 5; while(temp != 0){ count +=temp; temp /= 5; } return count; }
对的,就是这么简单的几句代码,就解决了,以前的以上那些好几行的代码。这个算法是基于第二种算法的出来的,第二种想到了,那些数的阶乘末尾有零,这个算法就想到了5的倍数。具体的分析法,去查看这个链接。https://blog.csdn.net/nwsuaf_uestc/article/details/78788932