Hackerrank: Extra Long Factorials Solution
Basically the multiply strings problemApproach
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()78 const res = []9 let carry = 01011 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 }1617 carry && res.push(carry)1819 return res.reverse().join("")20}2122const splitToDigitAndZeros = num => {23 const n = num.length24 return num.split("").map((digit, i) => [digit, n - i - 1])25}2627var multiply = function (num1, num2) {28 num1 = splitToDigitAndZeros(num1)29 num2 = splitToDigitAndZeros(num2)3031 let res = "0"3233 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)3738 res = addStrings(res, temp)39 }40 }4142 return String(res)43}44//45// LeetCode Multiply Strings (end)4647function extraLongFactorials(n) {48 let res = 149 for (let i = 1; i <= n; i++) res = multiply(String(res), String(i))50 return res51}
References
Comments
Loading comments...
Tags
hackerrank
math
string
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
Hackerrank: Compare the Triplets
Sep 17, 2022
Previous Post
Hackerrank: Grading Students
Sep 17, 2022