Skip to content

Instantly share code, notes, and snippets.

@chrisbodhi
Last active July 27, 2017 16:29
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 chrisbodhi/2a6dd58beee936fe7137e0ddb8c31d4d to your computer and use it in GitHub Desktop.
Save chrisbodhi/2a6dd58beee936fe7137e0ddb8c31d4d to your computer and use it in GitHub Desktop.
Given a string containing alphanumeric characters, calculate sum of all numbers present in the string.
function sumFromString(str) {
let sum = 0;
let acc = '0';
for (var i = 0; i < str.length; i +=1) {
if (parseInt(str[i])) {
acc += str[i]
if (i === (str.length - 1)) {
sum += parseInt(acc);
}
} else {
sum += parseInt(acc);
acc = '0';
}
}
return sum;
}
// sumFromString('a4gnh7j');
// => 11
// sumFromString('rgb5ny774bsdfg6');
// => 785
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment