Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mohamedhayibor/2901762e585fa73e7980 to your computer and use it in GitHub Desktop.
Save mohamedhayibor/2901762e585fa73e7980 to your computer and use it in GitHub Desktop.
function reverse(val) {
return val.split('').reverse().join('')
}
function add(a, b) {
var rBig, rSmall;
if ( Number(a) < Number(b) ) {
rBig = reverse(b);
rSmall = reverse(a);
} else {
rBig = reverse(a);
rSmall = reverse(b);
}
var carry = 0, digit = 0, total = '';
for (var i = 0; i < rBig.length; i ++) {
digit = Number(rBig[i]) + (Number(rSmall[i]) || 0) + carry;
carry = (digit > 9) ? Math.floor(digit / 10) : 0;
total = ( String(digit > 9 ? digit % 10 : digit) ).concat(total);
}
// handle last carry if any
if (carry == 1) {
total = ('1').concat(total);
}
// while first digits are '0' pop them off
while (total[0] === '0') total = total.slice(1);
return total;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment