Last active
February 3, 2016 22:28
-
-
Save mohamedhayibor/2901762e585fa73e7980 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
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