Tuesday, 2 August 2016

Calculate sum of all numbers present in a string

Given a string containing alphanumeric characters, calculate sum of all numbers present in the string.

Input:  1abc23
Output: 24

Input:  sudhakar4sudhakar
Output: 4

Input:  1abc2x30yz67
Output: 100

Input:  123abc
Output: 123
 
 

The only tricky part in this question is multiple consecutive digits and considering as one number.
The idea is very simple. We scan each character of the input string and if a number is formed by consecutive characters of the string, we increment the result by that amount.
Below is its  implementation –
#include <iostream>
using namespace std;
/
int findSum(string str)
{
    // A temporary string
    string temp = "";
    // holds sum of all numbers present in the string
    int sum = 0;
    
    for (char ch: str)
    {
        // if current character is a digit
        if (isdigit(ch))
            temp += ch;
        // if current character is an alphabet
        else
        {
            // increment sum by number found earlier
            // (if any)
            sum += atoi(temp.c_str());
            // reset temporary string to empty
            temp = "";
        }
    }
    // atoi(temp.c_str()) takes care of trailing
    // numbers
    return sum + atoi(temp.c_str());
}
// Driver code
int main()
{
    // input alphanumeric string
    string str = "12abc20yz68";
    cout << findSum(str);
    return 0;
}
Output:

100
 
 
Time complexity of above solution is O(n) where n is length of the string.

No comments:

Post a Comment