String to Integer - Write your own atoi()
Last Updated :
24 Mar, 2025
Given a string s, the task is to convert it into integer format without utilizing any built-in functions. Refer the below steps to know about atoi() function.
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.
The basic idea is to follow the atoi() algorithm in order and covering all the edge cases:
- Skip the leading whitespaces by iterating from the first character.
- Now, check for at most one sign character ('+' or '-') and maintain a sign variable to keep track of the sign of the number.
- Finally, read all the digits and construct the number until the first non-digit character is encountered or end of the input string is reached.
- While constructing the number, if the number becomes greater than 231 - 1, print 231 - 1. Similarly, if the number becomes less than -231, print -231.
How to check if the number is greater than 231 - 1 or smaller than -231 ?
The naive way is to use a data type which has size greater than 32 bits like long, BigInteger to store the number. However, we can also use 32-bit integer by appending the digits one-by-one and for each digit, check if appending current digit to the number will make it underflow (< -231) or overflow(> 231- 1). While appending a digit to the current number, we can have 3 cases:
Case 1: current number < (231 - 1)/10 or current number > -231/10: Simply append the digit to the current number as it won't cause overflow/underflow.
Case 2: current number > (231 - 1)/10 or current number < -231/10: Return (231 - 1) in case of overflow and -231 in case of underflow.
Case 3: current number = (231 - 1)/10 or current number = -231/10: In this case, if current number = (231 - 1)/10, then only 0-7 digits can be appended and if current number = -231/10, then only 0-8 digits can be appended.
In the below implementation, we are constructing the absolute value of the number, so we can simply compare with (231 - 1)/10 and avoid comparing with -231/10.
C++
#include <bits/stdc++.h>
using namespace std;
int myAtoi(char* s) {
int sign = 1, res = 0, idx = 0;
// Ignore leading whitespaces
while (s[idx] == ' ') {
idx++;
}
// Store the sign of number
if (s[idx] == '-' || s[idx] == '+') {
if(s[idx++] == '-')
sign = -1;
}
// Construct the number digit by digit
while (s[idx] >= '0' && s[idx] <= '9') {
// handling overflow/underflow test case
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && s[idx] - '0' > 7)) {
return sign == 1 ? INT_MAX : INT_MIN;
}
// Append current digit to the result
res = 10 * res + (s[idx++] - '0');
}
return res * sign;
}
int main() {
char s[] = " -0012g4";
// -0012g4
cout << myAtoi(s);
return 0;
}
C
#include <stdio.h>
#include <limits.h>
int myAtoi(char* s) {
int sign = 1, res = 0, idx = 0;
// Ignore leading whitespaces
while (s[idx] == ' ') {
idx++;
}
// Store the sign of number
if (s[idx] == '-' || s[idx] == '+') {
if (s[idx++] == '-') {
sign = -1;
}
}
// Construct the number digit by digit
while (s[idx] >= '0' && s[idx] <= '9') {
// Handling overflow/underflow test case
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && s[idx] - '0' > 7)) {
return sign == 1 ? INT_MAX : INT_MIN;
}
// Append current digit to the result
res = 10 * res + (s[idx++] - '0');
}
return res * sign;
}
int main() {
char s[] = " -0012g4";
printf("%d", myAtoi(s));
return 0;
}
Java
class GfG {
static int myAtoi(String s) {
int sign = 1, res = 0, idx = 0;
// Ignore leading whitespaces
while (idx < s.length() && s.charAt(idx) == ' ') {
idx++;
}
// Store the sign of number
if (idx < s.length() && (s.charAt(idx) == '-'
|| s.charAt(idx) == '+')) {
if (s.charAt(idx++) == '-') {
sign = -1;
}
}
// Construct the number digit by digit
while (idx < s.length() && s.charAt(idx) >= '0'
&& s.charAt(idx) <= '9') {
// Handling overflow/underflow test case
if (res > Integer.MAX_VALUE / 10 ||
(res == Integer.MAX_VALUE / 10 && s.charAt(idx) - '0' > 7)) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
// Append current digit to the result
res = 10 * res + (s.charAt(idx++) - '0');
}
return res * sign;
}
public static void main(String[] args) {
String s = " -0012g4";
System.out.println(myAtoi(s));
}
}
Python
def myAtoi(s: str) -> int:
sign = 1
res = 0
idx = 0
# Ignore leading whitespaces
while idx < len(s) and s[idx] == ' ':
idx += 1
# Store the sign of number
if idx < len(s) and (s[idx] == '-' or s[idx] == '+'):
if s[idx] == '-':
sign = -1
idx += 1
# Construct the number digit by digit
while idx < len(s) and '0' <= s[idx] <= '9':
# Append current digit to the result
res = 10 * res + (ord(s[idx]) - ord('0'))
# Handling overflow/underflow test case
if res > (2**31 - 1):
return sign * (2**31 - 1) if sign == 1 else -2**31
idx += 1
return res * sign
s = " -0012g4"
print(myAtoi(s))
C#
using System;
class GfG {
public static int MyAtoi(string s) {
int sign = 1, res = 0, idx = 0;
// Ignore leading whitespaces
while (idx < s.Length && s[idx] == ' ') {
idx++;
}
// Store the sign of number
if (idx < s.Length && (s[idx] == '-' || s[idx] == '+')) {
if (s[idx] == '-')
sign = -1;
idx++;
}
// Construct the number digit by digit
while (idx < s.Length && s[idx] >= '0' && s[idx] <= '9') {
// Handling overflow/underflow test case
if (res > Int32.MaxValue / 10 ||
(res == Int32.MaxValue / 10 && s[idx] - '0' > 7)) {
return sign == 1 ? Int32.MaxValue : Int32.MinValue;
}
// Append current digit to the result
res = 10 * res + (s[idx] - '0');
idx++;
}
return res * sign;
}
static void Main() {
string s = " -0012g4";
Console.WriteLine(MyAtoi(s));
}
}
JavaScript
function myAtoi(s) {
let sign = 1, res = 0, idx = 0;
// Ignore leading whitespaces
while (idx < s.length && s[idx] === ' ') {
idx++;
}
// Store the sign of number
if (idx < s.length && (s[idx] === '-' || s[idx] === '+')) {
if (s[idx] === '-') {
sign = -1;
}
idx++;
}
// Construct the number digit by digit
while (idx < s.length && s[idx] >= '0' && s[idx] <= '9') {
// Handling overflow/underflow test case
if ((res > Math.pow(2, 31) / 10) || ((res === Math.floor(Math.pow(2, 31) / 10)) && (s[idx] - '0' > 7))) {
return sign === 1 ? (Math.pow(2, 31) - 1) : -Math.pow(2, 31);
}
// Append current digit to the result
res = 10 * res + (s[idx] - '0');
idx++;
}
return (res * sign == -0 ? 0 : res * sign);
}
const s = " -0012g4";
console.log(myAtoi(s));
Working:
- Time Complexity: O(n), Only one traversal of the string is needed.
- Auxiliary Space: O(1), As no extra space is required.
Related Articles:
Write your won atof() that takes a string (which represents a floating point value) as an argument and returns its value as double.
Similar Reads
Javascript Program To Write Your Own atoi()
The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer. Syntax: int atoi(const char strn) Parameters: The function accepts one parameter strn which refers to
5 min read
Convert a String to an Integer using Recursion
Given a string str representing a string, the task is to convert the given string into an integer.Examples: Input: str = "1235" Output: 1235Explanation: "1235" is converted to the integer 1235 by extracting and combining its digits.Input: str = "0145" Output: 145 ApproachTo recursively converts a nu
3 min read
Recursive Implementation of atoi()
The atoi() function takes a string (which represents an integer) as an argument and returns its value. We have discussed iterative implementation of atoi(). How to compute recursively? Approach: The idea is to separate the last digit, recursively compute the result for the remaining n-1 digits, mult
4 min read
Introduction to Strings - Data Structure and Algorithm Tutorials
Strings are sequences of characters. The differences between a character array and a string are, a string is terminated with a special character â\0â and strings are typically immutable in most of the programming languages like Java, Python and JavaScript. Below are some examples of strings:"geeks"
7 min read
Program to Encrypt a String using ! and @
Given a string, the task is to encrypt this string using ! and @ symbols, alternatively. While encrypting the message the encrypted format must repeat the symbol as many times as the letter position in Alphabetical order. Examples: Input: string = "Ab" Output: !@@ Explanation: Position of 'A' in alp
11 min read
Program to check if input is an integer or a string
Write a function to check whether a given input is an integer or a string. Definition of an integer : Every element should be a valid digit, i.e '0-9'. Definition of a string : Any one element should be an invalid digit, i.e any symbol other than '0-9'. Examples: Input : 127Output : IntegerExplanati
15+ min read
Different ways to access characters in a given String in C++
String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. There are several ways to access substrings and individual characters of a string. The string class supports the following functions for this purpose: operator[]at()subst
4 min read
Program to convert a given number to words | Set 2
Write code to convert a given number into words. Examples: Input: 438237764Output: forty three crore eighty two lakh thirty seven thousand seven hundred and sixty four Input: 999999Output: nine lakh ninety nine thousand nine hundred and ninety nine Input: 1000Output: one thousand Explanation: 1000 i
13 min read
std::basic_string::at in C++
Returns a reference to the character at the specified location pos. The function automatically checks whether pos is the valid position of a character in the string (i.e., whether pos is less than the string length), throwing an out_of_range exception if it is not. Syntax: reference at (size_type po
1 min read
Rearrange a string in the form of integer sum followed by the minimized character
Given a string including lowercase alphabets and numeric digits. The task is to construct another string which consists of the sum of digits followed by the sum of all alphabets minimized to a single character. If no numeric digit is present add 0 to the string. Note: Alphabet summation is done in t
5 min read