VOOZH about

URL: https://www.geeksforgeeks.org/dsa/write-your-own-atoi/

⇱ String to Integer - Write your own atoi() - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

String to Integer - Write your own atoi()

Last Updated : 14 Apr, 2026

Given a string s, convert it into integer format without utilizing any built-in functions. Refer the below steps to know about atoi() function.

  • Skip any leading whitespaces.
  • Check for a sign ('+' or '-'), default to positive if no sign is present.
  • Read the integer by ignoring leading zeros until a non-digit character is encountered or end of the string is reached. If no digits are present, return 0.
  • If the integer is greater than 231 – 1, then return 231 – 1 and if the integer is smaller than -231, then return -231.

Examples:

Input: s = "-123"
Output: -123

Input: s = " -"
Output: 0
Explanation: No digits are present, therefore 0.

Input: s = " 1231231231311133"
Output: 2147483647
Explanation: The converted number is greater than 231 - 1, therefore print 231 - 1 = 2147483647.

Input: s = "-999999999999"
Output: -2147483648
Explanation: The converted number is smaller than -231, therefore print -231= -2147483648.

Input: s = " -0012gfg4"
Output: -12
Explanation: Nothing is read after -12 as a non-digit character 'g' was encountered.

Iterative Approach - O(n) Time and O(1) Space

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.

How to check if the number is greater than 231 - 1 or smaller than -231 ?

The naive way is to use a data type larger than 32 bits like long or BigInteger to store the number. However, we can also use a 32-bit integer by appending the digits one-by-one and, for each digit, checking whether appending it will cause overflow.

Since we construct the number as a positive value and apply the sign at the end, we only need to check against 231 - 1. While appending a digit to the current number, we can have 3 cases:
Case 1: current number < (231 - 1)/10 then simply append the digit to the current number as it will not cause overflow.
Case 2: current number > (231 - 1)/10 then return 231 - 1 in case of overflow.
Case 3: current number = (231 - 1)/10 then in this case, only digits from 0 to 7 can be appended safely. If the next digit is greater than 7, return 231 - 1.


Output
-12

Recursive Approach - O(n) Time and O(n) Space

Process the string recursively by skipping whitespaces, determining the sign, and building the number one digit at a time. At each recursive step, check for overflow and stop when a non-digit character is encountered or the string ends.


Output
-12

Related Articles:

Write your own atoi() that takes a string (which represents a floating point value) as an argument and returns its value as double.

Comment