Implementation of atoi()

A while ago I had an interesting interview question with a big tech company. The question was straight forward: Implement atoi() to convert a string to int.

Some restrictions apply:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Solution:

The way to handle this problem is to ignore all the restrictions at first. Think about how to implement atoi in a perfect world. This is pretty simple:

you would want to look at ASCII table. At each c

  • Look at ASCII table and define the starting value of ‘0’ (this is 48)
  • Subtract 48 from each ascii value of each character
  • add them together and return the new int

An example: “123” str[0] = ‘1’; str[1] = ‘2’; str[2] = ‘3’
So if we get the ASCII value of ‘1’ which is 49 and we subtract 48 from it we end up with 1 the int value. Remember this is 100 and not just one in our final number; so a quick implementation would be:

Now this is all nice an easy, but now think how you will handle all the other monster values such as negative sign; positive sign, white spaces, illegal characters, empty strings, etc…

Here is my code for this problem:

Tags:  , , ,

Leave a reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.