Helper Function: Convert String to Number
April 26, 2016
Print permutations of string replaced with digits
April 26, 2016

Helper Function: Return the terminating number in a string

Given a string that is terminating with digits (eg. ‘Kamal1234’). Write a function which accept this string and return the integer at the end.

Input String: 'Kamal1234'
Output (int): 1234
Input String: 'Moksha023Kam05'
Output (int):5

Solution:

The first challenge is to find the position after which all the characters are digits. Once we find that, then our task if to just convert string to number.
We need a minor modification in the function to convert string to number because we need a start point now.
Below is the complete code.

int strToNum(char* str, int start)
{
    int num = 0;
    for(int i=start; str[i]!='\0'; i++)
    {
        int digit = str[i] - '0';
        num = num*10 + digit;
    }
    return num;
}
/** We don't need n (size of string) parameter, because it can be derived. kept it just for the sake of simplicity
 */
int numberAtEnd(char*str, int n)
{
    int i=pos-1;
    while(i>=0 && isDigit(str[i]))
        i--;
    // i points to one place before the first digit. So Increment it
    i++;
    int number = strToNum(str, i);
}

Leave a Reply

Your email address will not be published. Required fields are marked *