Write a program that will calculate the number of trailing zeros in a factorial of a given number.javascript
http://mathworld.wolfram.com/...html
$$N! = 1 * 2 * 3 * 4 ... N$$java
zeros(12) = 2 # 1 2 3 .. 12 = 479001600
that has 2 trailing zeros 4790016(00)
Be careful 1000! has length of 2568 digital numbers.git
只有当有2*5
出现的时候,末尾才有可能出现0,而2的数量远大于5,因此咱们只须要计算在N!中,有多少个5.函数
function zeros (n) { var num = 0; while ( n > 4 ) { n = Math.floor(n/5); num += n; } return num; }
Math.floor()
和 parseInt()
的区别在上面的解答中,用到了Math.floor()
对数字进行向下取整,咱们知道parseInt()
也能达到一样的效果,那二者有什么区别吗?code
1. 功能不一样 htm
Math.floor(x)
:对数字进行向下取整。ip
parseInt(str, [radix])
:函数可解析数字或者字符串,并返回其整数部分。其中radix
为可选参数,默认为10进制。字符串
Math.floor('123'); // NaN parseInt('123'); // 123 // 字符串首字符为数字 parseInt('123a'); // 123 // 字符串首字符为非数字 parseInt('a123'); // NaN
2. Math.floor()
和 parseInt()
在对负数进行取整时,结果是有差别的。get
Math.floor(-1.3); // -2 parseInt(-1.3); // -1