The Wayback Machine - https://web.archive.org/web/20210301162728/https://www.geeksforgeeks.org/sum-of-numbers-formed-by-consecutive-digits-present-in-a-given-string/
Skip to content
Related Articles

Related Articles

Sum of numbers formed by consecutive digits present in a given string
  • Last Updated : 01 Mar, 2021

Given a string S consisting of digits [0 – 9] and lowercase alphabets, the task is to calculate the sum of all numbers represented by continuous sequences of digits present in the string S.

Examples:

Input: S = “11aa32bbb5”
Output: 48
Explanation: 
The consecutive sequence of numbers present in the string S are {11, 32, 5}.
Therefore, sum = 11 + 32 + 5 = 48

Input: s = “5an63ff2”
Output: 70

Approach: Follow the steps below to solve the problem:



  • Initialize a variable, say curr, to store the current sequence of consecutive digits
  • Iterate over the characters of the string.
  • If the current character is not a digit, add the current value of curr to the final answer. Reset curr to 0.
  • Otherwise, append the current digit to curr.
  • Finally, return the final answer.

Below is the implementation of the above approach:

C++




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to calculate the sum of
// numbers formed by consecutive
// sequences of digits present in the string
int sumOfDigits(string s)
{
    // Stores consecutive digits
    // present in the string
    int curr = 0;
  
    // Stores the sum
    int ret = 0;
  
    // Iterate over characters
    // of the input string
    for (auto& ch : s) {
  
        // If current character is a digit
        if (isdigit(ch)) {
  
            // Append current digit to curr
            curr = curr * 10 + ch - '0';
        }
        else {
  
            // Add curr to sum
            ret += curr;
  
            // Reset curr
            curr = 0;
        }
    }
  
    ret += curr;
    return ret;
}
  
// Driver Code
int main()
{
    string S = "11aa32bbb5";
    cout << sumOfDigits(S);
    return 0;
}


Output:

48

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :