原题目
Write a program that will calculate the number of trailing zeros in a factorial of a given number.
http://mathworld.wolfram.com/...
$$N! = 1 * 2 * 3 * 4 ... N$$
zeros(12) = 2 # 1 2 3 .. 12 = 479001600
that has 2 trailing zeros 4790016(00)
Be careful 1000! has length of 2568 digital numbers.
My solution
只有当有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()
也能达到同样的效果,那两者有什么区别吗?
1. 功能不同
Math.floor(x)
:对数字进行向下取整。parseInt(str, [radix])
:函数可解析数字或者字符串,并返回其整数部分。其中radix
为可选参数,默认为10进制。
Math.floor('123'); // NaN
parseInt('123'); // 123
// 字符串首字符为数字
parseInt('123a'); // 123
// 字符串首字符为非数字
parseInt('a123'); // NaN
2. Math.floor()
和 parseInt()
在对负数进行取整时,结果是有差异的。
Math.floor(-1.3); // -2
parseInt(-1.3); // -1
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。