Skip to content

Instantly share code, notes, and snippets.

@anupamkumar
Created September 20, 2016 23:08
Show Gist options
  • Save anupamkumar/df9bb26f1d7d58f8f7f62b443c2ff502 to your computer and use it in GitHub Desktop.
Save anupamkumar/df9bb26f1d7d58f8f7f62b443c2ff502 to your computer and use it in GitHub Desktop.
Calculate sum of all numbers present in a string
// Calculate sum of all numbers present in a string
// Given a string containing alphanumeric characters, calculate sum of all numbers present in the string.
// Examples:
// Input: 1abc23
// Output: 24
// Input: geeks4geeks
// Output: 4
// Input: 1abc2x30yz67
// Output: 100
// Input: 123abc
// Output: 123
///Analysis
// find the numbers in onepass and add them
// go character by character and if the character is a number then keep reading the number till we run out of numbers
// parse the string and add it to sum
// runtime = O(N) , one pass
function solution(str) {
var sum=0;
var tempn=0;
var tempns="";
for(var i=0;i<str.length;i++) {
if(str[i] == '1' || str[i] == '2' || str[i] == '3' || str[i] == '4' || str[i] == '5' || str[i] == '6' || str[i] == '7' || str[i] == '8' || str[i] == '9' || str[i] == '0') {
while(str[i] == '1' || str[i] == '2' || str[i] == '3' || str[i] == '4' || str[i] == '5' || str[i] == '6' || str[i] == '7' || str[i] == '8' || str[i] == '9' || str[i] == '0') {
tempns = tempns + str[i];
i++;
}
i--;
tempn = parseInt(tempns);
sum = sum + tempn;
tempn = 0;
tempns = "";
}
}
return sum;
}
console.log(solution("1abc23"));
console.log(solution("geeks4geeks"));
console.log(solution("1abc2x30yz67"));
console.log(solution("123abc"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment