![]() |
VOOZH | about |
Given a string S containing alphanumeric characters, The task is to calculate the sum of all numbers present in the string.
Examples:
Input: 1abc23
Output: 24
Explanation: 1 + 23 = 24Input: geeks4geeks
Output: 4Input: 1abc2x30yz67
Output: 100
Scan each character of the input string and if a number is formed by consecutive characters of the string, then increment the result by that amount. The only tricky part of this question is that multiple consecutive digits are considered one number.
Follow the below steps to implement the idea:
Below is the implementation of the above approach:
100
Time complexity: O(N) where n is length of the string.
Auxiliary Space: O(N) where n is length of the string.
The idea is to recursively traverse over the string and find out the numbers then add these numbers to the result, at last return the result.
Follow the below steps to implement the idea:
Below is the implementation of the above approach:
100
Time Complexity: O(N), where N is the size of the given string.
Auxiliary Space: O(N), in worst case it can cost O(N) recursive calls
The idea is to use inbuilt function Python RegEx.
Below is the Implementation of above approach:
100
Time complexity: O(n) where n is length of the string.
Auxiliary Space: O(n) where n is length of the string.