lintcode2 尾部的零
这题就是在求阶乘后面的0,我第一次想的方法很简单,先乘出来然后在除10,肯定可以了。但是这个的时间复杂度超了
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. int res =1; int tmp=0; for(int i =1;i<=n;i++){ res = res*i; } while(res%10==0 ) { tmp++; } return tmp; } }
所以我们使用获取能被5整除的数字的方法来求值
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. //int res =1; long q = n; long count = 0; while (q!=0){ count +=q/5; q = q/5; } return count; } }
其实是个数学问题,和你的编程能力没什么关系。。。
浙公网安备 33010602011771号