Problem 8

Abstract / Summary

Convert a string to an integer following specific rules for whitespace, signs, digits, and bounds.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0008.cpp

class Solution {
public:
    int myAtoi(string s) {
        while (!s.empty() && s[0] == ' ')
            s.erase(s.begin());

        if (s.empty())
            return 0;

        bool isNeg = false;
        if (s[0] == '+')
        {
            s.erase(s.begin());
        }
        else if (s[0] == '-')
        {
            isNeg = true;
            s.erase(s.begin());
        }

        int64_t x = 0;
        while (!s.empty() && s[0] >= '0' && s[0] <= '9')
        {
            auto digit = s[0] - '0';
            s.erase(s.begin());

            x = x*10 + digit;

            if (x > std::numeric_limits<int>::max())
                break;
        }

        if (isNeg)
        {
            x = -x;
            x = max<int64_t>(std::numeric_limits<int>::min(), x);
        }
        else
        {
            x = min<int64_t>(std::numeric_limits<int>::max(), x);
        }

        return x;
    }
};
45 lines | 962 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 21% (10+ million submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation converts a character sequence into a 32-bit signed integer while respecting the rules of the classic “atoi” problem. It processes the input string step-by-step: discarding leading blanks, detecting an optional sign, accumulating decimal digits, and finally clamping the result to the range of a signed 32-bit integer. The code relies on standard library utilities for limits and for safe arithmetic in a wider type.

Trimming Leading Whitespace

The first loop removes any leading space characters. By repeatedly erasing the first element while it is a space, the string is reduced to its first non-space character or becomes empty.

while (!s.empty() && s[0] == ' ')
    s.erase(s.begin());

If the string becomes empty after this step, the function returns zero, handling the case where the input consists solely of whitespace.

Sign Detection

After whitespace removal, the code checks for an explicit ‘+’ or ‘-’ sign. A boolean flag records negativity. When a sign character is present, it is removed from the string so that subsequent processing sees only the digit sequence.

bool isNeg = false;
if (s[0] == '+')
{
    s.erase(s.begin());
}
else if (s[0] == '-')
{
    isNeg = true;
    s.erase(s.begin());
}

This logic correctly treats a missing sign as positive and ensures that a sign without following digits still results in zero after the digit-parsing loop.

Digit Accumulation

The core conversion loop reads characters while they are decimal digits. Each digit is transformed from its ASCII code to a numeric value, the running total is multiplied by ten, and the digit is added. The accumulator x is a 64-bit integer, which prevents overflow during the multiplication and addition steps.

int64_t x = 0;
while (!s.empty() && s[0] >= '0' && s[0] <= '9')
{
    auto digit = s[0] - '0';
    s.erase(s.begin());

    x = x*10 + digit;

    if (x > std::numeric_limits<int>::max())
        break;
}

The loop stops early if the intermediate value exceeds the maximum 32-bit signed integer, preventing unnecessary work on the remaining characters.

Clamping to 32-Bit Range

After digit collection, the sign is applied. For a negative result, the code negates the accumulator and then clamps it to the lower bound of a 32-bit signed integer. For a positive result, it clamps to the upper bound. The max and min functions guarantee that the final value never exceeds the representable range.

if (isNeg)
{
    x = -x;
    x = max<int64_t>(std::numeric_limits<int>::min(), x);
}
else
{
    x = min<int64_t>(std::numeric_limits<int>::max(), x);
}

The function then returns the clamped value as an int.

Edge Cases Handled

The algorithm gracefully handles an input that is empty after whitespace removal, returning zero. It also correctly processes strings that contain only a sign character without digits, again yielding zero because the digit loop never executes. Non-digit characters that appear after the numeric prefix cause the digit loop to stop, leaving the already-parsed portion as the result. Overflow is prevented by the early break in the accumulation loop and by the final clamping step, ensuring that values larger than INT_MAX become INT_MAX and values smaller than INT_MIN become INT_MIN.

Performance Optimizations

The code avoids repeated conversion of the entire string by operating directly on the mutable std::string. Erasing the first character after it has been processed eliminates the need for an index variable and keeps the loop conditions simple. Using a 64-bit accumulator sidesteps overflow checks inside the multiplication, allowing the loop to run with minimal arithmetic overhead. The early exit when the accumulator exceeds INT_MAX reduces the number of iterations for very long numeric prefixes, saving time on inputs that would otherwise be truncated. Finally, the use of std::numeric_limits provides compile-time constants for the bounds, avoiding any runtime calculation of the limits.

written by openai gpt

ELI5 - Simplified Explanation

Imagine this code is like a tiny robot that is an expert at finding hidden numbers inside a messy pile of text. When you give the robot a jumbled string, it starts by sweeping away any empty spaces at the very front, just like clearing away dust so it can see clearly.

Once the front is clean, the robot peeks at the first character to see if it has a special sign. If it sees a plus sign, it ignores it because numbers are positive by default. If it sees a minus sign, it makes a little mental note that the final answer needs to be turned into a negative number.

After checking for the sign, the robot looks for the actual digits. It picks up each number character one by one and turns it into a real math number. Every time it finds a new number, it multiplies what it already has by ten and adds the new digit to the end, just like building a tower taller by stacking blocks one at a time. It keeps doing this until it runs out of numbers or hits a character that is not a digit.

Finally, the robot has to be careful because sometimes a very long string might try to make a number way too big for it to hold. If the number creates a tower that is too tall, the robot chops it down to the largest or smallest size that fits safely in its memory. If the robot made a note that the number should be negative, it flips the sign and makes sure it stays within the allowed limits so everything stays neat and tidy.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 29 | median = 5 | μ = 5.52 | σ = 1.43

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ C Python Java C# JS Go PHP
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Java
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, JavaScript, PHP, Python
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Java
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
53 links | 36 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'String to Integer atoi 🔥| Leetcode 8 | String'
Ayushi Sharma 17 mins
String to Integer atoi 🔥| Leetcode 8 | String
YouTube video 'String to Integer 🔥🔥🔥 | Recursive |  atoi() implementation | V.V. Imp | Medium'
Ayushi Sharma 14 mins
String to Integer 🔥🔥🔥 | Recursive | atoi() implementation | V.V. Imp | Medium
YouTube video 'STRING TO INTEGER (ATOI) | PYTHON | LEETCODE # 8'
Cracking FAANG 16 mins
STRING TO INTEGER (ATOI) | PYTHON | LEETCODE # 8
YouTube video 'Google Engineer Explains - LeetCode #8 - String to Integer (atoi) - Solution (Python)'
Google Engineer Explains 20 mins
Google Engineer Explains - LeetCode #8 - String to Integer (atoi) - Solution (Python)
YouTube video 'String to Integer (atoi) Python Solution - LeetCode #8'
Professor Oakes 8 mins
String to Integer (atoi) Python Solution - LeetCode #8
YouTube video 'Leetcode #8: String to Integer (atoi) - Java tutorial'
Chatterjee Tutoring 7 mins
Leetcode #8: String to Integer (atoi) - Java tutorial
YouTube video 'String to Integer (atoi) LeetCode 8 | Easy & Clear Explanation for Beginners'
CodingNinja 7 mins
String to Integer (atoi) LeetCode 8 | Easy & Clear Explanation for Beginners
YouTube video 'String to Integer atoi | Top Interview | Facebook Microsoft'
Naresh Gupta 11 mins
String to Integer atoi | Top Interview | Facebook Microsoft
YouTube video 'String to Integer (atoi) - Leetcode Problem 8 Explained | Coding Interview Question'
Web Coder Abhishek 9 mins
String to Integer (atoi) - Leetcode Problem 8 Explained | Coding Interview Question
YouTube video 'Leetcode Question 8 "String to Integer (atoi)" in Javascript'
Ghumman Tech 9 mins
Leetcode Question 8 "String to Integer (atoi)" in Javascript
YouTube video 'Day 41: Solving LeetCode Coding Problems | String to Integer (atoi) Problem | 150 Days Challenge'
Prep Insta 29 mins
Day 41: Solving LeetCode Coding Problems | String to Integer (atoi) Problem | 150 Days Challenge
YouTube video 'LeetCode: 8. String to Integer  - atoi (Visualized)'
Code With Zi 13 mins
LeetCode: 8. String to Integer - atoi (Visualized)
YouTube video 'Google Coding Interview Question | Leetcode 8 | String to Integer (atoi)'
WorkWithGoogler 14 mins
Google Coding Interview Question | Leetcode 8 | String to Integer (atoi)
YouTube video 'LeetCode - 8. String to Integer (atoi) | String | Java'
Orkhan Gasanov 7 mins
LeetCode - 8. String to Integer (atoi) | String | Java
YouTube video '8. String to Integer (atoi) (Leetcode Easy)'
Programming Live with Larry 16 mins
8. String to Integer (atoi) (Leetcode Easy)
YouTube video 'Solve String to Integer (atoi) in Python | LeetCode #8, Step-by-Step Solution'
que8 4 mins
Solve String to Integer (atoi) in Python | LeetCode #8, Step-by-Step Solution
YouTube video 'ASMR Leetcode #8 : String to Integer (atoi) Python solution'
ExtremeProgrammer 7 mins
ASMR Leetcode #8 : String to Integer (atoi) Python solution
YouTube video 'Amazon Software Engineer Interview Preparation - Part 18 LC  8 String to Integer (atoi)'
Ghumman Tech 12 mins
Amazon Software Engineer Interview Preparation - Part 18 LC 8 String to Integer (atoi)
YouTube video 'LeetCode 8 | String to Integer (atoi) | Rules | Java'
Sleepy Cracker 8 mins
LeetCode 8 | String to Integer (atoi) | Rules | Java
YouTube video '8. String to Integer (atoi) |  Approach 1: Follow the Rules | O(N)| Leetcode | Medium | Javascript'
Software Interviews Prep 23 mins
8. String to Integer (atoi) | Approach 1: Follow the Rules | O(N)| Leetcode | Medium | Javascript
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality