This article is participating in the nuggets team online activity, clickCheck spring recruitment positions in big factories

I. Title Description:

Design a function to compute the factorial of a number. For example, 1*2*3*… 1000 results.

This question is not exactly the same in Leetcode, please refer to this similar question: sword refers to Offer 66. Building product Arrays

Example 1:

Input: 3 Output: 6Copy the code

Note:

  • The sum of the product of all elements does not overflow the 32-bit integer
  • a.length <= 100000

Ii. Analysis of Ideas:

Idea 1:

For large numbers, we combine large numbers with arrays, and use arrays to store large numbers.

For example, to calculate the factorial of 50, we can do this:

  • 1*2=2, store 2 in a[0],

  • Next, a[0]*3:2*3=6, store 6 in a[0],

  • The following is a[0]* 4:6 *4=24, which is a two-digit number, then 24%10==4 is stored in a[0], 24/10==2 is stored in a[1]

  • A [0]*5, a[1]*5+num:

    1. 4 * 5 = 20, a[0]=0, num=2
    2. 2*5+num=12, a [1] = 2, num = 1
    3. a[2]=1
    4. A = [0, 2, 1]

.

Until you get to 50, and you store each digit.

Iii. Complete Code:

Idea 1:

function fn(nums) {
  let res = [1],
    count = 1,
    index = 0,
    carry = 0
  while (count <= nums) {
    index = 0
    while (index < res.length) {
      res[index] = res[index] * count + carry
      if (res[index] > 10) {
        carry = parseInt(res[index] / 10)
        res[index] = res[index] % 10
      } else {
        carry = 0
      }
      index++
    }
    if(carry ! =0) {
      res.push(carry)
      carry = 0
    }
    count++
  }
  return res.reverse().join(' ')}Copy the code

Iv. Summary:

When encountering large numbers, think of arrays to store data to avoid settlement results that overflow 32-bit integers.