Last active
April 7, 2022 14:49
-
-
Save mathenls/98acf4ae427d83cf26412e805ce14044 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
You are given 2 numbers as strings, and you need to sum them assuming that you can't simply parse them as integers | |
cause the numbers may be too big to be stored as an integer | |
Return the sum as a string | |
*/ | |
function sumStrings(str1, str2) { | |
const parsedDigits1 = str1 | |
.split('') | |
.reverse() | |
.map((digit) => parseInt(digit)); | |
const parsedDigits2 = str2 | |
.split('') | |
.reverse() | |
.map((digit) => parseInt(digit)); | |
const biggerNumber = parsedDigits1.length > parsedDigits2.length ? [...parsedDigits1] : [...parsedDigits2]; | |
const smallerNumber = parsedDigits2.length < parsedDigits1.length ? [...parsedDigits2] : [...parsedDigits1]; | |
const digitsSums = biggerNumber.map((digit, index) => { | |
return digit + (smallerNumber[index] >= 0 ? smallerNumber[index] : 0); | |
}); | |
return processCarrys(digitsSums).reverse().join(''); | |
} | |
function processCarrys(digitsSums) { | |
const digitSumsCopy = [...digitsSums]; | |
return digitSumsCopy.map((sum, index) => { | |
if (sum >= 10 && digitSumsCopy[index + 1] >= 0) { | |
digitSumsCopy[index + 1] += 1; | |
return sum % 10; | |
} | |
return sum; | |
}); | |
} | |
function test(str1, str2, solution) { | |
const res = sumStrings(str1, str2) | |
const isCorrect = res === solution ? "Correct" : "Incorrect" | |
console.log(`${str1} + ${str2} = ${res} \t=>\t${isCorrect}, expected ${solution}`) | |
} | |
test('1', '1', '2') | |
test('9', '1', '10') | |
test('999', '2', '1001') | |
test('10001', '1', '10002') | |
test('1', '10001', '10002') | |
test('10009', '10001', '20010') | |
test('299', '12', '311') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment