Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:45
Show Gist options
  • Save rfprod/42d44431042660116bcf4f96746fc800 to your computer and use it in GitHub Desktop.
Save rfprod/42d44431042660116bcf4f96746fc800 to your computer and use it in GitHub Desktop.
Sum Strings As Integers
function sumStrings(a,b) {
let result = '';
const long = (a.length < b.length) ? b : a;
let short = (long === a) ? b : a;
let pass = 0;
while (long.length > short.length) {
short = '0' + short;
}
for (let i = long.length - 1; i >= 0; i--) {
let sum = parseInt(long[i]) + parseInt(short[i]) + pass;
pass = (sum >= 10 && i !== 0) ? (sum - sum % 10) / 10 : 0;
//console.log(long[i] + '+' + short[i] + ': sum: ', sum, ' | pass: ', pass);
sum -= pass * 10;
result = sum.toString() + result;
}
while (result.indexOf('0') === 0) {
result = result.substr(1, result.length - 1);
}
return result;
}

Sum Strings As Integers

Sums provided strings, consisting of integers, as integers.

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment