Hackerrank: Extra Long Factorials Solution

Basically the multiply strings problem

Approach

We will reuse solution from an existing LeetCode problem Multiply Strings

Implementation

1// 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 = 0
10
11 for (let i = 0; i < maxLength; i++) {
12 const digitSum = Number(num1[i]) + Number(num2[i]) + carry
13 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.length
24 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 = 1
49 for (let i = 1; i <= n; i++) res = multiply(String(res), String(i))
50 return res
51}

References

Original problem

LeetCode: Multiply Strings

Comments

Loading comments...

Tags

hackerrank

math

string

Next Post

Hackerrank: Compare the Triplets

HoningJS

Search Posts