This post is completed by 2 users

  • 1
Add to List
Beginner

375. String to Integer (AtoI - ASCII to Integer)

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:

  1. check if the string is null, empty or "" then return 0.
  2. Trim the string from both ends.
  3. initialize sign = 1, result=0.
  4. 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.
  5. 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.
  6. Return result*sign.

Dry Run:

String input : "-123"
Initialize sign = 1, result = 0

processing character = '-'
sign = -1, result = 0;

processing character = '1'
num = '1'-'0' = 1
result = result*10 + 1 => 0*10+1 = 1

processing character = '2'
num = '2'-'0' = 2
result = result*10 + 2 => 1*10+2 = 12

processing character = '3'
num = '3'-'0' = 3
result = result*10 + 3 => 12*10+3 = 123

return sign*result => -1*123 = -123

Output:

Input String: '1234'
Converted Integer: 1234

Input String: '+555'
Converted Integer: 555

Input String: ' -03056'
Converted Integer: -3056

Input String: '-91283472332'
Converted Integer: -2147483648

Input String: '2.56'
Converted Integer: 2

Input String: '2147483648'
Converted Integer: 2147483647

Input String: '216 after words'
Converted Integer: 216

Input String: 'Before words 325'
Converted Integer: