Implement Atoi Function
Posted: 16 Dec, 2020
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.
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.
Given string : ”#messi10”, we return 10 as other characters “messi” are not numbers hence we skip them.
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.
1 <= T <= 50 0 <= N <= 3*10^3 Time Limit: 1 sec
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 :
- 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.
- 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.
- 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.
- 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.
- Finally, return the answer.
Posted: 22 Jul, 2021
Find All Subsets
Posted: 23 Jul, 2021
Print All Subsets
Posted: 23 Jul, 2021
Longest Common Prefix
Posted: 24 Jul, 2021
Posted: 29 Jul, 2021