Last active
July 27, 2017 16:29
-
-
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.
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 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