给定一个字符串,求其中连续数字所组成的数的总和

2023年 8月 29日 58.5k 0

给定一个字符串,求其中连续数字所组成的数的总和

问题陈述

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

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论