Created
July 20, 2017 13:18
-
-
Save AnwarShahriar/ac4dd259494587f5b0d4a2f822cd3657 to your computer and use it in GitHub Desktop.
This implements big integer addition in a naive way
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
let x = '12345678901234567890'; | |
let y = '12345678901234567890'; | |
let maxLen = Math.max(x.length, y.length) | |
if (maxLen !== x.length) { | |
let tempX = y; | |
y = x; | |
x = tempX; | |
} | |
if (x.length !== y.length) { | |
let padLen = x.length - y.length; | |
let zeros = ''; | |
for (let i = 0; i < padLen; i++) { | |
zeros += 0; | |
} | |
y = zeros + y; | |
} | |
let arr = []; | |
let carry = 0; | |
for (let i = x.length - 1; i >= 0; i--) { | |
let sum = Number(x[i]) + Number(y[i]) + carry; | |
carry = Math.floor(sum / 10); | |
arr.push(sum > 9 ? sum - 10 : sum); | |
} | |
if (carry !== 0) { | |
arr.push(carry); | |
} | |
let res = ''; | |
for (let i = arr.length - 1; i >= 0; i--) { | |
res += String(arr[i]); | |
} | |
console.log(res); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment