I am not sure why do they expect the following output -2147483648 instead of -91283472332

Because:

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.

So if the extracted number is larger than 2 ** 31 - 1, the returned number should be 2 ** 31 - 1 instead.

Similarly, if the extracted number is smaller than -(2 ** 31), instead return -(2 ** 31).

This would probably be easier with a regular expression:

const myAtoi = (str) => {
  const match = str.match(/^ *([+-]?\d+)/);
  if (!match) return;
  const num = Number(match[1]);
  return Math.max(
    Math.min(2 ** 31 - 1, num),
    -(2 ** 31)
  );
};

console.log(
  myAtoi('    123'),
  myAtoi('-456'),
  myAtoi('-9999999999999'),
  myAtoi('9999999999999')
);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Answer from CertainPerformance on Stack Overflow
🌐
LeetCode
leetcode.com › problems › string-to-integer-atoi
String to Integer (atoi) - LeetCode
Can you solve this real interview question? String to Integer (atoi) - Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: 1. Whitespace: Ignore any leading ...
Explore
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
Top Interview 150
Must-do List for Interview Prep
Premium
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
🌐
AlgoMonster
algo.monster › home › 8. string to integer (atoi)
8. String to Integer (atoi) - In-Depth Explanation
Skip leading whitespace: Any spaces at the beginning of the string should be ignored. Determine the sign: After skipping whitespace, check if the next character is '-' or '+'. If it's '-', the number will be negative. If it's '+' or neither sign is present, the number will be positive. Read digits: Convert consecutive digit characters into an integer.
🌐
Medium
medium.com › @rutujakbhombe19 › solving-leetcode-until-i-land-a-job-306a30914738
Leetcode 8 : String to Integer (atoi) | by Rutuja Bhombe | Medium
July 17, 2024 - Leetcode · Data Structures · Rutuja Bhombe · 4 min read · ·Jul 10, 2024 · -- 1 · Listen · Share · Press enter or click to view image in full size · solution · Implement the myAtoi(string s) function, which converts a string to a 32-bit ...
🌐
WalkCCC
walkccc.me › LeetCode › problems › 8
8. String to Integer (atoi) - LeetCode Solutions
LeetCode Solutions in C++23, Java, Python, MySQL, and TypeScript.
🌐
DEV Community
dev.to › grantdotdev › leetcode-8-string-to-integer-atoi-medium-33om
LeetCode 8: String to Integer (atoi) - Medium - DEV Community
September 21, 2025 - LeetCode's String to Integer (atoi) is a classic medium-difficulty coding problem that challenges you to convert a string representation of a number into an actual integer.
🌐
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 2
2

I am not sure why do they expect the following output -2147483648 instead of -91283472332

Because:

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.

So if the extracted number is larger than 2 ** 31 - 1, the returned number should be 2 ** 31 - 1 instead.

Similarly, if the extracted number is smaller than -(2 ** 31), instead return -(2 ** 31).

This would probably be easier with a regular expression:

const myAtoi = (str) => {
  const match = str.match(/^ *([+-]?\d+)/);
  if (!match) return;
  const num = Number(match[1]);
  return Math.max(
    Math.min(2 ** 31 - 1, num),
    -(2 ** 31)
  );
};

console.log(
  myAtoi('    123'),
  myAtoi('-456'),
  myAtoi('-9999999999999'),
  myAtoi('9999999999999')
);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 2
0

Have a look it this solution. As we are dealing with integers, they only hold 32-bit. 2^31 < x <= -2^31. So here we use a try catch as the 32bit integer can raise NumberFormat Exception which will be caught by the catch block.

class Solution {
    public int myAtoi(String str) {

        int flag=0, sign = 0;
        int n = str.length();
        StringBuilder st = new StringBuilder();
        int i =0;

        //clear white spaces
        while(i<n && str.charAt(i) == ' '){
            ++i;
        }

        //overflow of string
        if (i>=n){
            return 0;
        }

        //checking sign and not allowing more than one sign, will return 0 if there is ++,+-,--
        while(i<n && (str.charAt(i) == '+' || str.charAt(i) == '-')){
            if (sign >= 1){
                return 0;
            }
            else{
           st.append((str.charAt(i++) == '+') ? '+': '-');
            sign++;
            }

        }

        //checking if character is digit
        while(i<n && Character.isDigit(str.charAt(i))){
            st.append(str.charAt(i++));
            flag = 1;
        }

        //return 0 if no digits
        if(flag == 0)
            return 0;

        //to check if the number is within the int range
        try{
            return Integer.parseInt(st.toString());

        }
        catch(NumberFormatException e){
            return (st.charAt(0) == '-') ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }



    }
}

🌐
Red Quark
redquark.org › leetcode › 0008-string-to-integer-atoi
LeetCode #8 - String To Integer (atoi) | Red Quark
fun myAtoi(s: String): Int { var str = s // Base condition if (str.isEmpty()) { return 0 } // MAX and MIN values for integers val max = 2147483647 val min = -2147483648 // Trimmed string str = str.replace("^\\s+".toRegex(), "") // Counter var i = 0 // Flag to indicate if the number is negative val isNegative: Boolean = str.startsWith("-") // Flag to indicate if the number is positive val isPositive: Boolean = str.startsWith("+") if (isNegative) { i++ } else if (isPositive) { i++ } // This will store the converted number var number = 0.0 // Loop for each numeric character in the string iff nume
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › write-your-own-atoi
String to Integer - Write your own atoi() - GeeksforGeeks
Traverse the string from left to right, skipping whitespaces, handling the optional sign, and building the number digit by digit. At each step, ensure the value stays within 32-bit integer limits to avoid overflow.
Published: April 14, 2026
🌐
PREP INSTA
prepinsta.com › home › leetcode top 100 liked questions with solution › string to integer (atoi) leetcode solution
String to Integer (atoi) Leetcode Solution
January 9, 2024 - Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi function).
🌐
PROGIEZ
progiez.com › 8-string-to-integer-atoi-leetcode-solution
8. String To Integer (atoi) LeetCode Solution - Progiez
September 12, 2024 - class Solution { public int myAtoi(String s) { s = s.strip(); if (s.isEmpty()) return 0; final int sign = s.charAt(0) == '-' ? -1 : 1; if (s.charAt(0) == '+' || s.charAt(0) == '-') s = s.substring(1); long num = 0; for (final char c : s.toCharArray()) { if (!Character.isDigit(c)) break; num = num * 10 + (c - '0'); if (sign * num <= Integer.MIN_VALUE) return Integer.MIN_VALUE; if (sign * num >= Integer.MAX_VALUE) return Integer.MAX_VALUE; } return sign * (int) num; } } // code provided by PROGIEZ · class Solution: def myAtoi(self, s: str) -> int: s = s.strip() if not s: return 0 sign = -1 if s[0] == '-' else 1 if s[0] in {'-', '+'}: s = s[1:] num = 0 for c in s: if not c.isdigit(): break num = num * 10 + int(c) if sign * num <= -2**31: return -2**31 if sign * num >= 2**31 - 1: return 2**31 - 1 return sign * num #code by PROGIEZ · Explore all Leetcode problems solutions at Progiez here
🌐
Medium
medium.com › @harycane › string-to-integer-atoi-1e75325c5fd7
String to Integer (atoi). Implement atoi which converts a string… | by Hary Krishnan | Medium
August 1, 2018 - String to Integer (atoi) String to Integer (atoi) - LeetCode Implement atoi which converts a string to an integer. The function first discards as many whitespace characters …
🌐
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
🌐
YouTube
youtube.com › watch
String to Integer atoi 🔥| Leetcode 8 | String - YouTube
Timestamps:Problem explanation: 00:00Approaching the problem: 04:14Dry Run: 06:53Code Explanation: 13:15Complexity Analysis: 16:38Time Complexity : O(n)Space...
Published: January 14, 2022
🌐
Gitlab
memorylimitexceeded.gitlab.io › leetcode › problems › 0008-string-to-integer-atoi.html
8. String to Integer (atoi) | Leetcode Solutions
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.
🌐
LeetCode
leetcode.com › problems › add-strings › discuss › 528459 › Python-Solution-by-Converting-string-to-integer
Python Solution by Converting string to integer - Add Strings
March 4, 2020 - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
🌐
LeetCode
leetcode.com › discuss › study-guide › 5330348 › String-to-Integer-Atoi
String to-Integer-Atoi - Discuss - LeetCode
June 17, 2024 - // Step 1: Trim leading and trailing whitespaces s = s.trim(); // Step 2: Handle empty string after trimming if (s.length() == 0) { return 0; } // Step 3: Handle optional sign int sign = 1; int startIndex = 0; if (s.charAt(0) == '-') { sign ...
🌐
GitHub
gist.github.com › Rutvik17 › 7f455eb4b6f4972dd1f06eecb61225d1
String To Integer LeetCode · GitHub
String To Integer LeetCode. GitHub Gist: instantly share code, notes, and snippets.
🌐
YouTube
youtube.com › watch
STRING TO INTEGER (ATOI) | PYTHON | LEETCODE # 8 - YouTube
In this video we are solving a popular interview question at top tech companies Google, Facebook, Microsoft, and others. This is a pretty simple question but...
Published: March 2, 2022