# Hackerrank: Extra Long Factorials Solution

Basically the multiply strings problem

## Approach

We will reuse solution from an existing LeetCode problem Multiply Strings

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}// LeetCode Multiply Strings (start)2//3var addStrings = function (num1, num2) {4  const maxLength = Math.max(num1.length, num2.length)5  num1 = num1.padStart(maxLength, "0").split("").reverse()6  num2 = num2.padStart(maxLength, "0").split("").reverse()7
8  const res = []9  let carry = 010
11  for (let i = 0; i < maxLength; i++) {12    const digitSum = Number(num1[i]) + Number(num2[i]) + carry13    res.push(digitSum % 10)14    carry = Math.floor(digitSum / 10)15  }16
17  carry && res.push(carry)18
19  return res.reverse().join("")20}21
22const splitToDigitAndZeros = num => {23  const n = num.length24  return num.split("").map((digit, i) => [digit, n - i - 1])25}26
27var multiply = function (num1, num2) {28  num1 = splitToDigitAndZeros(num1)29  num2 = splitToDigitAndZeros(num2)30
31  let res = "0"32
33  for (const [digit1, numberOfZeros1] of num1) {34    for (const [digit2, numberOfZeros2] of num2) {35      let temp = String(digit1 * digit2)36      if (temp > 0) temp += "0".repeat(numberOfZeros1 + numberOfZeros2)37
38      res = addStrings(res, temp)39    }40  }41
42  return String(res)43}44//45// LeetCode Multiply Strings (end)46
47function extraLongFactorials(n) {48  let res = 149  for (let i = 1; i <= n; i++) res = multiply(String(res), String(i))50  return res51}```

## References

Original problem

LeetCode: Multiply Strings

hackerrank

math

string

## Next Post

Hackerrank: Compare the Triplets

Sep 17, 2022

Search Posts