Dada una string S que consta de dígitos [0 – 9] y letras en minúsculas, la tarea es calcular la suma de todos los números representados por secuencias continuas de dígitos presentes en la string S.
Ejemplos:
Entrada: S = “11aa32bbb5”
Salida : 48
Explicación:
La secuencia consecutiva de números presentes en la string S son {11, 32, 5}.
Por lo tanto, suma = 11 + 32 + 5 = 48Entrada: s = “5an63ff2”
Salida: 70
Enfoque: siga los pasos a continuación para resolver el problema:
- Inicialice una variable, digamos curr , para almacenar la secuencia actual de dígitos consecutivos
- Iterar sobre los caracteres de la string .
- Si el carácter actual no es un dígito, agregue el valor actual de curr a la respuesta final . Restablecer corriente a 0 .
- De lo contrario, agregue el dígito actual a curr .
- Finalmente, devuelva la respuesta final.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ Program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to calculate the sum of // numbers formed by consecutive // sequences of digits present in the string int sumOfDigits(string s) { // Stores consecutive digits // present in the string int curr = 0; // Stores the sum int ret = 0; // Iterate over characters // of the input string for (auto& ch : s) { // If current character is a digit if (isdigit(ch)) { // Append current digit to curr curr = curr * 10 + ch - '0'; } else { // Add curr to sum ret += curr; // Reset curr curr = 0; } } ret += curr; return ret; } // Driver Code int main() { string S = "11aa32bbb5"; cout << sumOfDigits(S); return 0; }
Java
// Java program to implement // the above approach import java.io.*; import java.util.*; class GFG { // Function to calculate the sum of // numbers formed by consecutive // sequences of digits present in the string static int sumOfDigits(String s) { // Stores consecutive digits // present in the string int curr = 0; // Stores the sum int ret = 0; // Iterate over characters // of the input string for(char ch : s.toCharArray()) { // If current character is a digit if (ch >= 48 && ch <= 57) { // Append current digit to curr curr = curr * 10 + ch - '0'; } else { // Add curr to sum ret += curr; // Reset curr curr = 0; } } ret += curr; return ret; } // Driver Code public static void main(String[] args) { String S = "11aa32bbb5"; System.out.print(sumOfDigits(S)); } } // This code is contributed by splevel62.
Python3
# Python3 program for the above approach # Function to calculate the sum of # numbers formed by consecutive # sequences of digits present in the string def sumOfDigits(s) : # Stores consecutive digits # present in the string curr = 0 # Stores the sum ret = 0 # Iterate over characters # of the input string for ch in s : # If current character is a digit if (ord(ch) >= 48 and ord(ch) <= 57) : # Append current digit to curr curr = curr * 10 + ord(ch) - ord('0') else : # Add curr to sum ret += curr # Reset curr curr = 0 ret += curr return ret # Driver Code S = "11aa32bbb5" print(sumOfDigits(S)) # This code is contributed by code_hunt.
C#
// C# Program to implement // the above approach using System; class GFG { // Function to calculate the sum of // numbers formed by consecutive // sequences of digits present in the string static int sumOfDigits(string s) { // Stores consecutive digits // present in the string int curr = 0; // Stores the sum int ret = 0; // Iterate over characters // of the input string foreach(char ch in s) { // If current character is a digit if (ch >= 48 && ch <= 57) { // Append current digit to curr curr = curr * 10 + ch - '0'; } else { // Add curr to sum ret += curr; // Reset curr curr = 0; } } ret += curr; return ret; } // Driver code static void Main() { string S = "11aa32bbb5"; Console.WriteLine(sumOfDigits(S)); } } // This code is contributed by divyeshrabadiya07.
Javascript
<script> // Javascript Program to implement // the above approach // Function to calculate the sum of // numbers formed by consecutive // sequences of digits present in the string function sumOfDigits(s) { // Stores consecutive digits // present in the string var curr = 0; // Stores the sum var ret = 0; // Iterate over characters // of the input string s.split('').forEach(ch => { // If current character is a digit if (parseInt(ch)) { // Append current digit to curr curr = curr * 10 + ch.charCodeAt(0) - '0'.charCodeAt(0); } else { // Add curr to sum ret += curr; // Reset curr curr = 0; } }); ret += curr; return ret; } // Driver Code var S = "11aa32bbb5"; document.write( sumOfDigits(S)); // This code is contributed by importantly. </script>
Producción:
48
Complejidad temporal: O(N)
Espacio auxiliar: O(1)