Table of Contents
Problem Statement
ExampleExample
Input
Output
Explanation
method one
algorithm
Example
Approach 2
Method 3
Conclusion
Home Backend Development C++ Given a string, find the sum of consecutive numbers in it

Given a string, find the sum of consecutive numbers in it

Aug 28, 2023 am 09:17 AM
string number continuous

Given a string, find the sum of consecutive numbers in it

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.

ExampleExample

Input

str = “12were43”
Copy after login

Output

55
Copy after login

Explanation

The sum of 12 and 43 is equal to 55.

Input

str = “1a2c3d”
Copy after login

Output

6
Copy after login

Explanation

The sum of 1, 2 and 3 is 6.

Input

str = “werderfrewsf”
Copy after login

Output

0
Copy after login

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.

method one

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 to 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 number, multiply the numeric value by 10 and add the current numeric value.

  • Step 4 - If the current character is not a number, add the value of the "number" variable to the "sum" variable and update the value of the "number" variable 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;
}
Copy after login

Output

The sum of consecutive digits in the given string is - 41
Copy after login
  • Time complexity - O(n), because we only use one loop.

  • Space Complexity − O(1) since 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 to an empty string. Also, define the 'sum' variable and initialize it to 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 or equal to 9, it means that the current character is a number.

  • 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;
}
Copy after login

Output

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

  • Space complexity − O(1)

Method 3

In this method, we use regular expressions to find matches of all numbers. After that we can convert the string to 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 - Again, update the string using the match().suffix() method. This way we won't get duplicate 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;
}
Copy after login

Output

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

  • Space complexity − O(1)

Conclusion

We learned three different ways to find the sum of consecutive numbers in a string. The last method is the most optimized code because it uses regular expressions. However, working with regular expressions can be difficult for beginners.

The above is the detailed content of Given a string, find the sum of consecutive numbers in it. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
Detailed explanation of the method of converting int type to string in PHP Detailed explanation of the method of converting int type to string in PHP Mar 26, 2024 am 11:45 AM

Detailed explanation of the method of converting int type to string in PHP In PHP development, we often encounter the need to convert int type to string type. This conversion can be achieved in a variety of ways. This article will introduce several common methods in detail, with specific code examples to help readers better understand. 1. Use PHP’s built-in function strval(). PHP provides a built-in function strval() that can convert variables of different types into string types. When we need to convert int type to string type,

How to determine whether a Golang string ends with a specified character How to determine whether a Golang string ends with a specified character Mar 12, 2024 pm 04:48 PM

Title: How to determine whether a string ends with a specific character in Golang. In the Go language, sometimes we need to determine whether a string ends with a specific character. This is very common when processing strings. This article will introduce how to use the Go language to implement this function, and provide code examples for your reference. First, let's take a look at how to determine whether a string ends with a specified character in Golang. The characters in a string in Golang can be obtained through indexing, and the length of the string can be

How to repeat a string in python_python repeating string tutorial How to repeat a string in python_python repeating string tutorial Apr 02, 2024 pm 03:58 PM

1. First open pycharm and enter the pycharm homepage. 2. Then create a new python script, right-click - click new - click pythonfile. 3. Enter a string, code: s="-". 4. Then you need to repeat the symbols in the string 20 times, code: s1=s*20. 5. Enter the print output code, code: print(s1). 6. Finally run the script and you will see our return value at the bottom: - repeated 20 times.

How to intercept a string in Go language How to intercept a string in Go language Mar 13, 2024 am 08:33 AM

Go language is a powerful and flexible programming language that provides rich string processing functions, including string interception. In the Go language, we can use slices to intercept strings. Next, we will introduce in detail how to intercept strings in Go language, with specific code examples. 1. Use slicing to intercept a string. In the Go language, you can use slicing expressions to intercept a part of a string. The syntax of slice expression is as follows: slice:=str[start:end]where, s

How to check if a string starts with a specific character in Golang? How to check if a string starts with a specific character in Golang? Mar 12, 2024 pm 09:42 PM

How to check if a string starts with a specific character in Golang? When programming in Golang, you often encounter situations where you need to check whether a string begins with a specific character. To meet this requirement, we can use the functions provided by the strings package in Golang to achieve this. Next, we will introduce in detail how to use Golang to check whether a string starts with a specific character, with specific code examples. In Golang, we can use HasPrefix from the strings package

PHP String Operation: Remove Extra Commas and Keep Only Commas Implementation Tips PHP String Operation: Remove Extra Commas and Keep Only Commas Implementation Tips Mar 28, 2024 pm 03:02 PM

PHP String Operation: Remove Extra Commas and Keep Only Commas Implementation Tips In PHP development, string processing is a very common requirement. Sometimes we need to process the string to remove extra commas and retain the only commas. In this article, I'll introduce an implementation technique and provide concrete code examples. First, let's look at a common requirement: Suppose we have a string containing multiple commas, and we need to remove the extra commas and keep only the unique comma. For example, replace "apple,ba

Detailed explanation of Golang string modification: dynamic adjustment and variability Detailed explanation of Golang string modification: dynamic adjustment and variability Apr 08, 2024 pm 03:27 PM

Strings in GoLang, although immutable, can be dynamically modified using the following technique: concatenating strings using string concatenation. Create a new string using string formatting. Modify the underlying byte slice of the string. Use mutable string types provided by third-party libraries.

PHP techniques for deleting the last two characters of a string PHP techniques for deleting the last two characters of a string Mar 23, 2024 pm 12:18 PM

As a scripting language widely used to develop web applications, PHP has very powerful string processing functions. In daily development, we often encounter operations that require deleting a string, especially the last two characters of the string. This article will introduce two PHP techniques for deleting the last two characters of a string and provide specific code examples. Tip 1: Use the substr function The substr function in PHP is used to return a part of a string. We can easily remove characters by specifying the string and starting position

See all articles