Skip to main content

Sum of Numbers in String

Problem​

Given a string str containing alphanumeric characters. The task is to calculate the sum of all the numbers present in the string.

Examples:​

Example 1:

Input:
str = 1abc23
Output: 24
Explanation: 1 and 23 are numbers in the string which is added to get the sum as 24.

Example 2:

Input:
str = geeks4geeks
Output: 4
Explanation: 4 is the only number, so the sum is 4.

Your task:​

The task is to complete the function findSum() which finds and returns the sum of numbers in the string.

  • Expected Time Complexity: O(N)O(N)
  • Expected Auxiliary Space: O(N)O(N)

Constraints:​

  • 1<=1<= length of the string <=105<=10^5
  • Sum of Numbers <=105<=10^5

Solution​

Python​

def findSum(self,s):
temp = "0"
Sum = 0
for ch in s:
if (ch.isdigit()):
temp += ch
else:
Sum += int(temp)
temp = "0"
return Sum + int(temp)

Java​

public static long findSum(String str) {
String temp = "0";
long Sum = 0;
for (char ch : str.toCharArray()) {
if (Character.isDigit(ch)) {
temp += ch;
}
else {
Sum += Long.parseLong(temp);
temp = "0";
}
}

Sum += Long.parseLong(temp);
return Sum;
}

C++​

int findSum(string str) {
string temp = "0";
int Sum = 0;
for (char ch : str) {
if (isdigit(ch)) {
temp += ch;
}
else {
Sum += stoi(temp);
temp = "0";
}
}
Sum += stoi(temp);
return Sum;
}

C​

int findSum(const char *str) {
char temp[20];
int Sum = 0;
int temp_index = 0;
for (const char *ptr = str; *ptr != '\0'; ptr++) {
if (isdigit(*ptr)) {
temp[temp_index++] = *ptr;
}
else {
temp[temp_index] = '\0';
Sum += atoi(temp);
temp_index = 0;
}
}
temp[temp_index] = '\0';
Sum += atoi(temp);
return Sum;
}
  • Time Complexity: O(N)O(N)
  • Auxiliary Space: O(N)O(N)