This post is completed by 1 user
|
Add to List |
385. String to Integer (AtoI - ASCII to Integer) - Recursive Solution
Objective: Write a recursive function to implement atoi, which converts string to an integer.
Rules for converting string to an integer.
- If the string is null or empty, Integer will be 0.
- The first character of the string may represent the sign of the integer. '+' or '-'
- Discard the white spaces if necessary.
- If String contains characters either before digits or after digits, ignore them.
Example:
Input String: 1234 Converted Integer: 1234 -------------------------------------------------- Input String: -03056 Converted Integer: -3056 -------------------------------------------------- Input String: -91283472332 Converted Integer: -2147483648 -------------------------------------------------- Input String: 2.56 Converted Integer: 2 -------------------------------------------------- Input String: 2147483643 Converted Integer: 2147483643 -------------------------------------------------- Input String: 216 after words Converted Integer: 216 -------------------------------------------------- Input String: Before words 325 Converted Integer: 325
Approach:
- check if the string is null, empty or "" then return 0.
- Trim the string from both ends.
- initialize sign = 1, result=0.
- Check if the first character of the input string is either '+' or '-', start the string process from index 1 and In the case of '-', do sign = -1 and remove the first character from the string.
- Now make a call to the recursive function, this function will calculate the ASCII value for the last character in the string and make to the recursive call with remaining string. Multiply the result of the remaining string with 10 and add ASCII value (calculated earlier) and return. (When adding ASCII, make sure that addition is not crossing MAX_VALUE of Integer, if it does then just return MAX_VALUE)
- Multiply the returned result with the sign. This will be the final answer.
Output:
Input String: '-1234' Converted Integer: -1234 Input String: '+555' Converted Integer: 555 Input String: ' -03056' Converted Integer: -3056 Input String: '-91283472332' Converted Integer: -2147483647 Input String: '2.56' Converted Integer: 256 Input String: '2147483648' Converted Integer: 2147483647 Input String: '216 after words' Converted Integer: 216 Input String: 'Before words 325' Converted Integer: 325