char digit = (char)(tmp.charAt(i) - '0');

In the ascii table, characters from '0' to '9' are contiguous. So, if you know that tmp.charAt(i) will return a character between 0 and 9, then subracting 0 will return the offset from zero, that is, the digit that that character represents.

Answer from Tom on Stack Overflow
🌐
LeetCode
leetcode.com › problems › string-to-integer-atoi
String to Integer (atoi) - LeetCode
Return the integer as the final result. Note:​​​​​​​ You must not use any built-in library function that converts a string to a number (for example, atoi, stoi, Integer.parseInt, int(), parseInt, Number()). Perform the conversion manually. Example 1: Input: s = "42" Output: 42 ·
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › write-your-own-atoi
String to Integer - Write your own atoi() - GeeksforGeeks
Write your own atoi() that takes a string (which represents a floating point value) as an argument and returns its value as double.
Published: April 14, 2026
🌐
AlgoMonster
algo.monster › home › 8. string to integer (atoi)
8. String to Integer (atoi) - In-Depth Explanation
Handle overflow: The result must be within the range of a 32-bit signed integer [-2^31, 2^31 - 1], which is [-2147483648, 2147483647]. If the number would overflow: ... The solution needs to carefully handle edge cases like empty strings, strings with only spaces, and integer overflow situations during the conversion process.
Top answer
1 of 2
8

All in all, that's a pretty good implementation in a number of key details.

Using the Character.isDigit() and Character.getNumericValue() methods are good to see.

The Math.* methods that handle the overflow conditions are good too.

I am not sure if you intended it, but you also correctly handle an obscure edge-case in 32-bit signed integer systems (not just Java), where Integer.MIN_VALUE is not the same as - Integer.MAX_VALUE ... and your code actually gets it right for an exact input of the text "-2147483648"

So, you have good details in your code.... and I can't see any broken edge-cases.

My only recommendation would be that a state-machine may make things simpler... with just one loop..... but the state-machine may be a bit messy too, although I think it works out better in the long run...

public static int rlAtoi(String str) {
    boolean started = false;
    boolean negative = false;
    int result = 0;
    try {
        for (char c : str.toCharArray()) {
            if (!started && Character.isWhitespace(c)) {
                // great, ignore it.
            } else if (!started && (c == '+' || c == '-')) {
                // great, a sign
                negative = c == '-';
                started = true;
            } else if (Character.isDigit(c)) {
                result = Math.multiplyExact(result, 10);
                result = Math.addExact(result, Character.getNumericValue(c));
                started = true;
            } else {
                // done....
                break;
            }
        }
    } catch (ArithmeticException e) {
        return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
    }
    return negative ? -result : result;
}

Note that in a raw performance benchmark, I suspect your solution will be (slightly) faster, but I prefer readability over small incremental performance gains, unless performance is extremely critical.

2 of 2
6

There is a duplicate test for the '-' char. I'd rewrite

boolean isNegative = false;
if (str.charAt(i) == '+' || str.charAt(i) == '-') {
    isNegative = str.charAt(i) == '-';
    ++i;
}

as

boolean isNegative = false;
if (str.charAt(i) == '-') {
    isNegative= true;
    ++i;
    }
else if (str.charAt(i) == '+')
    ++i;

I would also add support for hexadecimal numbers.

🌐
Arhantjain
programming.arhantjain.com › Java › String › STOI.html
LeetCode String to Integer (atoi) - Java Solutions
If the result exceeds the 32-bit signed integer range, we clamp it to INT_MIN or INT_MAX. This ensures we handle edge cases and invalid inputs gracefully. ... class Solution { public int myAtoi(String s) { boolean isFirstCharacter = true; int sign = 1; long num =0; for(int i=0;i<s.length();i++){ char ch = s.charAt(i); if(ch==' '){ //"334234 3423"; if(!isFirstCharacter) break; } else if(ch=='+'){ if(!isFirstCharacter) break; else{ sign = 1; isFirstCharacter = false; } } else if(ch=='-'){ if(!isFirstCharacter) break; else{ sign = -1; isFirstCharacter = false; } } else if(Character.isDigit(ch)){ num = num*10 + ch-'0'; if(num*sign>Integer.MAX_VALUE) return Integer.MAX_VALUE; else if(num*sign < Integer.MIN_VALUE) return Integer.MIN_VALUE; isFirstCharacter = false; } else break; } return (int)num*sign; } }
🌐
GitHub
github.com › doocs › leetcode › blob › main › solution › 0000-0099 › 0008.String to Integer (atoi) › README_EN.md
leetcode/solution/0000-0099/0008.String to Integer (atoi)/README_EN.md at main · doocs/leetcode · GitHub
Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. Rounding: If the integer is out of the 32-bit signed integer ...
Author: doocs
Find elsewhere
Top answer
1 of 1
2

Normally when parsing a String into an int, people expect it to be a static method

Having to create a class to do the computation is a bit bulky, and then you need to worry about synchronization (what happens if this class is shared across multiple threads?)

boolean isOverflow(int prev, int curr) {
    // prev = value at last iteration
    // curr = value after current iteration
    if (curr/10 == prev) {
        return false;
    }
    return true;
}

This method is already a great candidate to become static, it only relies on its two inputs to figure out if an overflow happened

boolean isNegative = false;
int i = 0; // string iterator position

void checkSign(String str) //uses i and isNegative

int signSolution(int solution) //uses isNegative

These are slightly more tricky, int signSolution(int solution) can just take another parameter: static int signSolution(int solution, boolean isNegative)

void checkSign(String str) would need to be included as part of the myAtoI method or be rewritten a bit

If we treat + as whitespace, then it would only need to worry about handling -

static boolean checkSign(String str, int i)
{
    return str.charAt(i) == '-';
}

And calls to checkSign(str); would instead be if(checkSign(str)) i++;


Be consistent. You're mixing for and while loops of similar structure

while (i < str.length() && str.charAt(i) == ' ')
    i++;
[...]
for (; i < str.length(); i++) {
    [...]
}

They can either both be for loops, or both be while loops, but mixing is unexpected

for(; i < str.length() && str.charAt(i) == ' '; i++);
[...]
for(; i < str.length(); i++)
{
    [...]
}

vs

while(i < str.length() && str.charAt(i) == ' ')
    i++;
[...]
while(i < str.length())
{
    [...]
    i++;
}

Checking "whitespace" currently only checks spaces

Instead of using str.charAt(i) == ' ', you can offload complicated functionality to another method (and be easier to change later)

static boolean isWhiteSpace(char c)
{
    return c == ' ';
}

Then if you'd like to include all whitespace (and + and mentioned above)

static boolean isWhiteSpace(char c)
{
    return Character.isWhitespace(c) || (c == '+');
}

Instances of if(bool) return true; else return false; are the same as just return bool;

if (curr/10 == prev) {
        return false;
}
return true;

Can be simplified to just

return curr / 10 != prev;

OptionalA:

Another way to check for overflow is to store the output as a long, and check if it overflows

public static int myAtoI(String str)
{
    long solution = 0;
    [...]
}

private static isOverflow(long num)
{
    return num == (int)num;
}

OptionalB:

Instead of adding the values and then flipping the result, you could subtract values if it's a negative number

🌐
Medium
medium.com › @soham-khade › 8-string-to-integer-atoi-leetcode-problem-java-042a26831f49
8. String to Integer (atoi) LeetCode Problem (Java) | by Soham | Medium
October 27, 2023 - Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32).
🌐
DEV Community
dev.to › jaspreet_singh_86ae1740ac › string-to-integer-atoi-2nki
String to Integer (atoi) - DEV Community
June 30, 2026 - class Solution { public int myAtoi(String s) { int i = 0; int n = s.length(); while (i < n && s.charAt(i) == ' ') i++; int sign = 1; if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) { if (s.charAt(i) == '-') sign = -1; i++; } int number = 0; while (i < n && Character.isDigit(s.charAt(i))) { int digit = s.charAt(i) - '0'; if (number > (Integer.MAX_VALUE - digit) / 10) { return sign == 1 ?
🌐
GitHub
github.com › awangdev › leet-code › blob › master › Java › 8. String to Integer (atoi).java
leet-code/Java/8. String to Integer (atoi).java at master · awangdev/leet-code · GitHub
* @param str: A string · * @return An integer · */ · public int atoi(String str) { · if (str == null || str.length() == 0) { · return 0; · } · str = str.replaceAll("\\s",""); · ...
Author: awangdev
🌐
JanBask Training
janbasktraining.com › community › java › how-can-i-implement-string-to-java-atoi
How can I implement string to java atoi? | JanBask Training Community
October 10, 2022 - I'm not sure about my checks against integer overflow, but here is my implementation: public int Atoi(String str) { int i = 0; while (i < str> ++i; } if (i == str.length()) { return 0; } boolean isNegative = false; if (str.charAt(i) == '+' || str.charAt(i) == '-') { isNegative = str.charAt(i) == '-'; ++i; } int result = 0; while (i < str> try { result = Math.multiplyExact(result, 10); result = Math.addExact(result, Character.getNumericValue(str.charAt(i))); } catch (ArithmeticException e) { return isNegative ?
🌐
Red Quark
redquark.org › leetcode › 0008-string-to-integer-atoi
LeetCode #8 - String To Integer (atoi) | Red Quark
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.
🌐
GitHub
github.com › leetcoders › LeetCode-Java › blob › master › StringtoInteger(atoi).java
LeetCode-Java/StringtoInteger(atoi).java at master · leetcoders/LeetCode-Java · GitHub
December 14, 2014 - Problem: String to Integer (atoi) Difficulty: Easy · Source: https://oj.leetcode.com/problems/string-to-integer-atoi/solution/ Notes: Implement atoi to convert a string to an integer.
Author: leetcoders
🌐
WalkCCC
walkccc.me › LeetCode › problems › 8
8. String to Integer (atoi) - LeetCode Solutions
LeetCode Solutions in C++23, Java, Python, MySQL, and TypeScript.
🌐
YouTube
youtube.com › watch
String To Integer (atoi) - 8. LeetCode - Java - YouTube
String To Integer (atoi) - 8. LeetCode - Java Github repo: https://github.com/teddysmithdev/LeetCodeJava2024LeetCode description: https://leetcode.com/proble...
Published: August 20, 2024
🌐
Blogger
massivealgorithms.blogspot.com › 2015 › 06 › leetcode-string-to-integer-atoi-java.html
Massive Algorithms: LeetCode 8 - String to Integer (atoi)
public int myAtoi(String str) { if (str.isEmpty()) return 0; int sign = 1, base = 0, i = 0, n = str.length(); while (i < n && str.charAt(i) == ' ') ++i; if (i < n && (str.charAt(i) == '+' || str.charAt(i) == '-')) { sign = (str.charAt(i++) == '+') ? 1 : -1; } while (i < n && str.charAt(i) >= ...
🌐
Stackademic
blog.stackademic.com › implement-atoi-ascii-to-integer-using-java-5d57445048c6
Implement Atoi (ASCII to Integer) using Java | by Vibhuti Singh Gaharwar | Stackademic
February 5, 2024 - Input: s = "21a" Output: -1 ... implements a function atoi (ASCII to Integer) that efficiently converts a string representing an integer to its corresponding integer value....
🌐
GitHub
gist.github.com › daifu › 4689019
Implement atoi to convert a string to an integer. · GitHub
Implement atoi to convert a string to an integer. GitHub Gist: instantly share code, notes, and snippets.