# int atoi( char* pStr )

Source: https://www.techinterview.org/post/526339864/int-atoi-char-pstr/
Updated: 2026-07-05 · techinterview.org

Problem: write the definition for this function *without using any built-in functions*. if pStr is null, return 0. if pStr contains non-numeric characters, either return 0 (ok) or return the number derived so far (better) (e.g. if its “123A”, then return 123). assume all numbers are positive. plus or minus signs can be considered non-numeric characters. in order to solve this program, the programmer must understand the difference between the integer 0 and the character ‘0’, and how converting ‘0’ to an int, will not result in 0. in other words, they have to understand what ascii is all about.

### Solution

string manipulation functions are great programming questions. they test whether the user can understand and translate into code simple algorithms. string functions test pointer arithmetic which usually shows [a knowledgeable programmer](http://www.joelonsoftware.com/articles/fog0000000073.html). also there are usually multiple solutions, some more efficient than others. plus people use them all the time so they should understand how they work. my favorite is [atoi](https://www.techinterview.org/post/3233474777/string-to-integer-atoi-edge-case-minefield/) and i start the problem like this:

`int atoi( char* pStr )`

write the definition for this function *without using any built-in functions*. if pStr is null, return 0. if pStr contains non-numeric characters, either return 0 (ok) or return the number derived so far (better) (e.g. if its “123A”, then return 123). assume all numbers are positive. plus or minus signs can be considered non-numeric characters. in order to solve this program, the programmer must understand the difference between the integer 0 and the character ‘0’, and how converting ‘0’ to an int, will not result in 0. in other words, they have to understand what ascii is all about. if they are stuck solving this problem, just ask them first to write:

`charToInt(char c)`

if they can’t do that then they basically missed half the problem. any moderately talented programmer who has a CS degree knows how to convert a char to an int. (note i said convert, not cast. `charToInt('9')` should return 9.)

when they start to solve the problem you will notice that they must make a choice in how they will process the string - from left to right or right to left. i will discuss both methods and the difficulties encountered in each.

"right to left" - this method starts at the right hand letter of the string and converts that character to an int. it then stores this value after promoting it to its correct "tens" place.


```
int atoi( char* pStr ) {   int iRetVal = 0;   int iTens = 1;   if ( pStr )  {    char* pCur = pStr;     while (*pCur)       pCur++;     pCur--;     while ( pCur >= pStr && *pCur <= '9' && *pCur >= '0' )     {       iRetVal += ((*pCur - '0') * iTens);      pCur--;       iTens *= 10;     }  }   return iRetVal; }
```

"left to right" - this method keeps adding the number and multiplying the result by ten before continuing to the next number. e.g. if you had "6234" and you processed from left to right you’d have 6, then if you kept reading you’d multiply your result by 10 (6*10) to add a zero for where the next number would go. 60, and then you’d slide the 2 into the zero place you just made. 62. do it again, 620, slide the next number in, 623.


```
int atoi( char* pStr ) {  int iRetVal = 0;    if ( pStr )  {    while ( *pStr && *pStr <= '9' && *pStr >= '0' )     {      iRetVal = (iRetVal * 10) + (*pStr - '0');      pStr++;    }  }   return iRetVal; }
```

i think the “left to right” method is a little bit cleaner, or maybe its just cooler. but both are “correct”.

remember that debugging code on paper is somewhat hard. most programmers aren’t used to studying code that much when you can just hit F-7, compile and see if the compiler barfs or not. if you notice an error, just ask them to step through a sample string drawing out what is happening with all the variables and the pointers in every step. they should find their mistake then and fix it (no points deducted).

## 2026 Update: Implementing atoi() — Edge Cases That Fail Interviews

Implementing `atoi()` (string to integer) is a classic interview question that tests attention to edge cases. A naive implementation fails 6+ of the standard test cases. Here's a production-quality implementation:


```
def my_atoi(s: str) -> int:
    """
    Implements C's atoi() with proper edge case handling.
    Rules: skip leading whitespace, handle sign, stop at non-digit,
    clamp to 32-bit signed integer range.
    """
    INT_MIN, INT_MAX = -2**31, 2**31 - 1
    i = 0
    n = len(s)

    # 1. Skip leading whitespace
    while i < n and s[i] == ' ':
        i += 1

    # 2. Handle sign
    sign = 1
    if i < n and s[i] in '+-':
        if s[i] == '-':
            sign = -1
        i += 1

    # 3. Parse digits (stop at first non-digit)
    result = 0
    while i < n and s[i].isdigit():
        digit = int(s[i])
        # Pre-overflow check: test BEFORE the multiply (avoids 64-bit math)
        if result > (INT_MAX - digit) // 10:
            return INT_MAX if sign == 1 else INT_MIN
        result = result * 10 + digit
        i += 1

    return sign * result

# Edge cases
test_cases = [
    ("42", 42),
    ("   -42", -42),
    ("4193 with words", 4193),
    ("words and 987", 0),       # Non-digit at start → 0
    ("-91283472332", -2147483648),  # Clamp to INT_MIN
    ("2147483648", 2147483647),    # Clamp to INT_MAX
    ("+-12", 0),                   # Multiple signs → 0
    ("", 0),                       # Empty string
]

for s, expected in test_cases:
    result = my_atoi(s)
    status = "✓" if result == expected else "✗"
    print(f"{status} atoi({s!r}) = {result} (expected {expected})")
```

**Common interview mistakes:**

- Forgetting to handle leading whitespace

- Not clamping to INT_MIN/INT_MAX on overflow

- Checking overflow *after* the multiply (too late — already overflowed)

- Allowing `"+-12"` or `"--12"` to parse as valid numbers

- Not stopping at the first non-digit character

**2026 interview tip:** LeetCode #8 (String to Integer) is still asked at Meta, Amazon, and Bloomberg. The pre-overflow check `result > (INT_MAX - digit) // 10` is the elegant trick that avoids using 64-bit arithmetic for overflow detection.
