问题陈述
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.
示例示例
Input
str = “12were43”
登录后复制
输出
55
登录后复制
Explanation
The sum of 12 and 43 is equal to 55.
Input
str = “1a2c3d”
登录后复制
输出
6
登录后复制
Explanation
1、2和3的和为6。
Input
str = “werderfrewsf”
登录后复制
输出
0
登录后复制
Explanation
It gives 0 in the output as the string contains no digit.
我们解决问题的逻辑是从给定的字符串中提取所有数字并求和。
方法一
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.
算法
-
步骤 1 - 将 'number' 和 'sum' 变量初始化为零。
-
Step 2 − Iterate through the string and check current character is between 0-9 using the isDigit() method.
-
步骤 3 - 如果当前字符是数字,则将数字值乘以10,并加上当前数字值。
-
第四步 - 如果当前字符不是数字,则将“number”变量的值添加到“sum”变量中,并将“number”变量的值更新为零。
-
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
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