VOOZH about

URL: https://www.geeksforgeeks.org/dsa/calculate-sum-of-all-numbers-present-in-a-string/

⇱ Calculate sum of all numbers present in a string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Calculate sum of all numbers present in a string

Last Updated : 20 Mar, 2023

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

Examples: 

Input:  1abc23
Output: 24
Explanation: 1 + 23 = 24

Input:  geeks4geeks
Output: 4

Input:  1abc2x30yz67
Output: 100

Approach:

Scan each character of the input string and if a number is formed by consecutive characters of the string, then increment the result by that amount. The only tricky part of this question is that multiple consecutive digits are considered one number.

Follow the below steps to implement the idea:

  • Create an empty string temp and an integer sum.
  • Iterate over all characters of the string.
    • If the character is a numeric digit add it to temp.
    • Else convert temp string to number and add it to sum, empty temp.
  • Return sum + number obtained from temp.

Below is the implementation of the above approach:


Output
100


Time complexity: O(N) where n is length of the string. 
Auxiliary Space: O(N) where n is length of the string.

Calculate sum of all numbers present in a string using recursion

The idea is to recursively traverse over the string and find out the numbers then add these numbers to the result, at last return the result

Follow the below steps to implement the idea:

  • Create an empty string temp and an integer sum.
  • Recursively traverse the characters for every index i from 0 to length - 1.
    • If i = N-1 then check if current character is a digit return str[i] - '0'.
    • Else return 0.
    • If str[i] is a digit.
      • Run a for loop with counter from i to N - 1.
        • If the character is a numeric digit add it to temp.
        • Else break.
      • Return sum of numeric value of temp + recur for index j.

Below is the implementation of the above approach:


Output
100

Time Complexity: O(N), where N is the size of the given string.
Auxiliary Space: O(N), in worst case it can cost O(N) recursive calls

Calculate sum of all numbers present in a string using Regex in Python:

The idea is to use inbuilt function Python RegEx

Below is the Implementation of above approach:


Output
100

Time complexity: O(n) where n is length of the string. 
Auxiliary Space: O(n) where n is length of the string.

Comment
Article Tags:
Article Tags: