Implement Atoi Function

Posted: 16 Dec, 2020
Difficulty: Easy


Try Problem

Given a string ‘STR’ of length 'N'. Implement the atoi function. If there are no numbers in the string, return 0.

In other words, given a string ‘STR’ convert the string to an integer.

Example :

Give string : ”123456”, we return the integer value ‘123456’.

The string can contain any ascii characters. If the character in the string is not a number, ignore it.

Example :

Given string : ”#messi10”, we return 10 as other characters “messi” are not numbers hence we skip them.
Note :
1. If the first char is ‘-’ it represents a minus sign and hence we return a negative integer.
2. If there is no number in the string, return 0.
3. It is guaranteed that the number is less than or equal to 10^9.
Input format :
The first line of input contains an integer ‘T’ denoting the number of test cases.
Then the test cases follow.

The only line of each test case contains the string ‘STR’.
Output format :
For each test case, return the integer formed by the given string.
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 50
0 <= N <= 3*10^3

Time Limit: 1 sec
Approach 1

We can solve the problem recursively by just checking if the current character is a digit or not. If yes, we add it in our number and then recursively check the complete string to construct the number.


 Here is the algorithm : 


  1. First of all, check if the number is a negative number or not. For that simply check if the first character of the string is a ‘-’ character or not.
  2. Then we use our recursive function helper which takes in 3 parameters ‘CURIDX’, ‘N’ and string ‘STR’ where ‘N’ is the number of characters in the string.
  3. Base case : If we are at the last character of the string.
    • If it is a number, we return that number.
    • else, we return 0.
  4. Then we recursively calculate the answer if the ‘CURIDX’ is a digit we multiply our answer by 10 to shift it to the right and then add this digit.
  5. Finally, return the answer.
Try Problem