宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

JS数据位数限制:https://www.cnblogs.com/wangmeijian/p/9217352.html
使用数组实现阶乘运算的过程:https://www.cnblogs.com/hiluna/p/8868175.html

JavaScript中的基本数据类Number是双精度浮点数,它可以表示的最大安全范围是正负9007199254740991,也就是2的53次方减一

CodeWars里的要求是不用JS提供的bigInt等数据类型,也不能使用其他插件

题目:
In mathematics, the factorial of integer n is written as n!. It is equal to the product of n and every integer preceding it. For example: 5! = 1 x 2 x 3 x 4 x 5 = 120

Your mission is simple: write a function that takes an integer n and returns the value of n!.

You are guaranteed an integer argument. For any values outside the non-negative range, return null, nil or None (return an empty string “” in C and C++). For non-negative numbers a full length number is expected for example, return 25! = “15511210043330985984000000” as a string.

For more on factorials, see http://en.wikipedia.org/wiki/Factorial

NOTES:

The use of BigInteger or BigNumber functions has been disabled, this requires a complex solution

I have removed the use of require in the javascript language.

答案:

function factorial(n){
  if(n<0){return null;}
  if(n==0 ||n==1){return "1";}
  let arr=[1];
  let temp=0; 
  for(let i=2; i<=n; i++){                                //取出2~n之间的数字
    for(let j=0,prior=0; j<arr.length ||prior!=0; j++){   //从个位数arr[0]开始相乘(有的时候进位的数字要放入arr[length+1],要增加一个判断条件prior!=0)
      temp = (j<arr.length)? arr[j]*i+prior : prior;      //temp存储相乘结果(记得加上prior)
      arr[j] = temp%10;                                   //更新当前位arr[j]
      prior= (temp-arr[j])/10;                            //算出进位
    }
  }
  return arr.reverse().join("");
}