Objective: 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 string may represent the sign of the integer. ‘+’ or ‘-‘
Discard the white spaces if necessary.
If any point, conversion of the string is not possible then stop the conversion and return the integer created out of already processed string.
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: 0
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.
Now iterate the string from left to right, one character at a time.
calculate the ASCII value of character, if ASCII value is in between 0 to 9 then do result = result * 10.( Keep track of result, it should not cross INT_MAX value, if it does then return INT_MAX*sign. The INT_MAX value is 2147483647).
If ASCII value is not between 0 to 9, then return the result, this will have a conversion for the already processed valid string.
Return result*sign.