Member-only story

Leetcode Explained: Implementing the Atoi Function (Medium)

Scott Cosentino
3 min readOct 7, 2019

--

Problem: Implement the atoi function, which converts a string into an integer

Problems involving reimplementing system and built in programming functions are great practice for learning programming techniques and logic. For this problem, it is very helpful to first outline all of the cases and situations we could encounter in the problem.

Here are the cases involved in this problem:

1. If the string contains any whitespace characters, they should be removed

2. The string can contain exactly one non whitespace character at the beginning that is either a “+” or “-“ sign

3. If there are any other characters before the digit, the result is 0

4. If there are any characters after the digits, they are ignored

5. If the number is greater than 231–1, or less than -231, the max value 231–1, or min value -231 is returned instead

Before starting with coding, let’s do a few quick examples to get an idea of the output we are expecting.

Input: “42”

Output: 42

This case is the easiest case we will encounter. In this case, we can just directly convert and we are done.

Input: “ -42”

Output: -42

This case involves a negative sign, which we keep since it is the first character

--

--

Scott Cosentino
Scott Cosentino

No responses yet