Created
October 10, 2020 18:26
-
-
Save ajmeese7/1c5dbd22612ccf9621c363d9a15a5c07 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
Please write a function that adds two large numbers represented by a string , such that the output is not expressed in scientific notation. | |
*/ | |
function add(a, b) { | |
let aNums = breakIntoManageableParts(a); | |
let bNums = breakIntoManageableParts(b); | |
let remainder = 0, bigSum = ""; | |
while (aNums.length > 0 || bNums.length > 0) { | |
let lastA = getNumToAdd(aNums); | |
let lastB = getNumToAdd(bNums); | |
let sum = String(lastA + lastB + remainder); | |
bigSum = sum + bigSum; // Adds higher numbers on the left | |
remainder = sum.length > 15 ? parseInt(sum.charAt(0)) : 0; | |
// Remove numbers already added | |
aNums.pop(); | |
bNums.pop(); | |
} | |
console.log("Big sum:", bigSum); | |
return bigSum; | |
} | |
/** Breaks the number up from right to left in segments of 15 */ | |
function breakIntoManageableParts(bigassNum) { | |
let smallerParts = []; | |
while (bigassNum.length > 15) { | |
let endIndex = bigassNum.length - 16; | |
smallerParts.unshift(bigassNum.substr(endIndex)); | |
bigassNum = bigassNum.substr(0, endIndex); | |
} | |
if (bigassNum.length > 0) smallerParts.unshift(bigassNum); | |
return smallerParts; | |
} | |
/** Replace non-existant values with 0 for addition purposes */ | |
function getNumToAdd(numArray) { | |
return numArray.length > 0 ? parseInt(numArray[numArray.length - 1]) : 0; | |
} | |
console.log(add('3156551651651','6513515126516516') === '6516671678168167'); | |
console.log(add('2334234232342342346675467678567676764456345134123523', '23034298372387187498752364987564957845') === '2334234232342365380973840065755175516821332699081368'); | |
console.log(add('1616516516516516516516151551', '466161651651651651616516511') === '2082678168168168168132668062'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment