Sum of numbers formed by consecutive digits present in a given string


Problem Statement

We have given a string str containing the numeric and alphabetical characters. We need to find the sum of all numbers represented by a continuous sequence of digits available in the given string.

Sample Examples

Input

str = “12were43”

Output

55

Explanation

The sum of 12 and 43 is equal to 55.

Input

str = “1a2c3d”

Output

6

Explanation

The sum of 1, 2, and 3 is 6.

Input

str = “werderfrewsf”

Output

0

Explanation

It gives 0 in the output as the string contains no digit.

Our logic to solve the problem is to extract all numbers from the given string and sum them.

Approach 1

In this approach, we will use isDigit() method to check whether the current character is a digit. Also, we multiply the current value of the number by 10 and add the current character to the number if the current character is a digit.

Algorithm

  • Step 1 − Initialize the ‘number’ and ‘sum’ variables with zero.

  • Step 2 − Iterate through the string and check current character is between 0-9 using the isDigit() method.

  • Step 3 − If the current character is a digit, multiply the number value by 10, and add the current digit value.

  • Step 4 − If the current character is not a digit, add the value of the ‘number’ variable to the ‘sum’ variable, and update the ‘number’ variable’s value to zero.

  • Step 5 − Once the iteration of the loop completes, add the value of the ‘number’ to the ‘sum’ variable and return the value of the sum variable.

Example

#include <bits/stdc++.h>
using namespace std;
// function to return the sum of the consecutive number present in the string
int getSumOfDigits(string str){
   // store the current number
   int number = 0;
   // Stores total sum
   int sum = 0;
   // Traverse the string
   for (auto &ch : str){
      // If the current character is between '0' and '9', append it to the number
      if (isdigit(ch)) {
         number = number * 10 + ch - '0';
      } else {
         // 	if the current character is not between '0' and '9', add 'number' to the sum and reset 'number'
         sum += number;
         number = 0;
      }
   }
   // if the number is greater than 0, add it to sum
   sum += number;
   return sum;
}
int main(){
   string str = "6we24er5rd6";
   cout << "The sum of consecutive digits in the given string is - " << getSumOfDigits(str);
   return 0;
}

Output

The sum of consecutive digits in the given string is - 41
  • Time complexity − O(n), As we use a single loop.

  • Space complexity − O(1), as we don’t use any extra space.

Approach 2

In this approach, we use the ASCII values of the character to check whether the current character is a digit. Also, we append characters to the ‘number’ variable until we get digits in the string and use the atoi() method to extract the number from the string.

Algorithm

  • Step 1 − Define the ‘number’ variable and initialize it with an empty string. Also, define the ‘sum’ variable and initialize it with 0.

  • Step 2 − Use for loop to traverse the string and get each character of the string.

  • Step 3 − If c-‘0’ is greater than or equal to zero and less than equal to 9, it means the current character is a digit.

  • Step 4 − If the current character is a digit, append it to the ‘number’ string.

  • Step 5 − If the current character is not a digit, use the c_str() method to convert the number string to a character array and pass it as a parameter of the atoi() method to convert the string to a number. Also, update the number string with the “” value.

    The atoi() method returns a number if the string is convertible to a number; Otherwise, it returns zero.

  • Step 6 − Once the iteration of for loop completes, again use the atoi() method to convert the string to a number and add to the sum value.

Example

#include <bits/stdc++.h>
using namespace std;
// function to return the sum of the consecutive numbers present in the string
int getSumOfDigits(string str){
   string number = "";
   // to store the sum of all the consecutive numbers
   int sum = 0;
   // traverse the string
   for (char c : str){
      // if the current character is between 0 to 9
      if (c - '0' >= 0 && c - '0' <= 9){
         // append it to the number string
         number += c;
      }
      // if the current character is an alphabet
      else {
         // convert string to an array of characters and pass it to atoi() function
         sum += atoi(number.c_str());
         // reset temporary string to empty
         number = "";
      }
   }
   // if the number is greater than 0, add it to sum
   sum += atoi(number.c_str());
   return sum;
}
int main(){
   string str = "11aa32bbb5";
   cout << "The sum of consecutive digits in the given string is - " << getSumOfDigits(str);
   return 0;
}

Output

The sum of consecutive digits in the given string is - 48
  • Time complexity − O(N)

  • Space complexity − O(1)

Approach 3

In this approach, we use the regular expression to find all matches for the numbers. After that, we can convert the string to a number and add it to the sum variable.

Algorithm

  • Step 1 − Define the regex pattern.

  • Step 2 − Use the regex_search() method to find the match for the number string.

  • Step 3 − Make iterations using a while loop as long as we find matches.

  • Step 4 − In the while loop, use the stoi() method to convert the string to a number and add it to the sum variable.

  • Step 5 − Also, update the string using match().suffix() method. So we don’t get repeated matches.

Example

#include <bits/stdc++.h>
using namespace std;
// Function to calculate the sum of the numbers found in the string
int getSumOfDigits(string str){
   // regex pattern to find the numbers in the string
   regex pattern("d+");
   smatch match;
   // variable to store the sum of the numbers
   int sum = 0;
   // using the regex_search() function to find the numbers
   while (regex_search(str, match, pattern)){
      // adding the numbers to the sum variable
      sum += stoi(match[0].str());
      // update the string
      str = match.suffix().str();
   }
   return sum;
}
int main(){
   // input alphanumeric string
   string str = "abc23@12";
   cout << "The sum of consecutive digits in the given string is - " << getSumOfDigits(str);
   return 0;
}

Output

The sum of consecutive digits in the given string is - 0
  • Time complexity − O(N), as regex finds matches by iterating through the string.

  • Space complexity − O(1)

Conclusion

We learned three different approaches to finding the sum of consecutive digits presented in the string. The last approach is the most optimized code, as it uses the regex. However, for beginners, it can be hard to use regular expressions.

Updated on: 18-Jul-2023

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements