Sum of numbers formed by consecutive digits present in a given string
Last Updated :
06 Sep, 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++
#include <bits/stdc++.h>
using namespace std;
int sumOfDigits(string s)
{
int curr = 0;
int ret = 0;
for ( auto & ch : s) {
if ( isdigit (ch)) {
curr = curr * 10 + ch - '0' ;
}
else {
ret += curr;
curr = 0;
}
}
ret += curr;
return ret;
}
int main()
{
string S = "11aa32bbb5" ;
cout << sumOfDigits(S);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static int sumOfDigits(String s)
{
int curr = 0 ;
int ret = 0 ;
for ( char ch : s.toCharArray())
{
if (ch >= 48 && ch <= 57 )
{
curr = curr * 10 + ch - '0' ;
}
else
{
ret += curr;
curr = 0 ;
}
}
ret += curr;
return ret;
}
public static void main(String[] args)
{
String S = "11aa32bbb5" ;
System.out.print(sumOfDigits(S));
}
}
|
Python3
def sumOfDigits(s) :
curr = 0
ret = 0
for ch in s :
if ( ord (ch) > = 48 and ord (ch) < = 57 ) :
curr = curr * 10 + ord (ch) - ord ( '0' )
else :
ret + = curr
curr = 0
ret + = curr
return ret
S = "11aa32bbb5"
print (sumOfDigits(S))
|
C#
using System;
class GFG
{
static int sumOfDigits( string s)
{
int curr = 0;
int ret = 0;
foreach ( char ch in s)
{
if (ch >= 48 && ch <= 57)
{
curr = curr * 10 + ch - '0' ;
}
else
{
ret += curr;
curr = 0;
}
}
ret += curr;
return ret;
}
static void Main() {
string S = "11aa32bbb5" ;
Console.WriteLine(sumOfDigits(S));
}
}
|
Javascript
<script>
function sumOfDigits(s)
{
var curr = 0;
var ret = 0;
s.split( '' ).forEach(ch => {
if (parseInt(ch)) {
curr = curr * 10 + ch.charCodeAt(0) - '0' .charCodeAt(0);
}
else {
ret += curr;
curr = 0;
}
});
ret += curr;
return ret;
}
var S = "11aa32bbb5" ;
document.write( sumOfDigits(S));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...