Skip to content

Instantly share code, notes, and snippets.

@AnwarShahriar
Created July 20, 2017 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnwarShahriar/ac4dd259494587f5b0d4a2f822cd3657 to your computer and use it in GitHub Desktop.
Save AnwarShahriar/ac4dd259494587f5b0d4a2f822cd3657 to your computer and use it in GitHub Desktop.
This implements big integer addition in a naive way
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