Open In App

Java Program To Write Your Own atoi()

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The atoi() function in Java converts a numeric string into an integer. Unlike Java’s built-in methods like Integer.parseInt(), we will implement our own version of atoi() with different levels of error handling and special case handling.

Syntax:  

int myAtoi(String str);

Parameter: str The numeric string is to be converted to an integer.

Return Value:

  • If str is a valid integer string, the function returns its integer equivalent.
  • If str is invalid (e.g., contains non-numeric characters), the function returns 0.

Different Ways to Create Own atoi() Function

Approach 1: Simple Conversion Without Special Cases

Steps to Implement:

  • Initialize the result as 0.
  • Start from the first character of the string.
  • For each character:
    • Convert it to a digit using (s[i] - '0').
    • Update result = result * 10 + digit.
  • Return the final integer result.

Illustration:

Java
// Basic atoi() function without handling special cases
class Geeks {
  
    // Function to convert string to integer
    static int myAtoi(String s) {
   
        // Handle null or empty string
        if (s == null || s.isEmpty()) {
            return 0;
        }

        int res = 0;

        // Traverse each character
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);

            // If non-numeric character is found, return 0
            if (ch < '0' || ch > '9') {
                return 0;
            }

            res = res * 10 + (ch - '0');
        }

        return res;
    }

    public static void main(String[] args) {
        String s = "12345";
        System.out.println(myAtoi(s)); 
    }
}

Output
12345
  • Time Complexity: O(N), where N is the length of the string. We traverse the string once.
  • Auxiliary Space: O(1), as only a few integer variables are used.

Approach 2: Handling Negative Numbers

This approach supports negative numbers by checking if the first character is "-".

Steps to Implement:

  • Initialize result = 0, sign = 1, and i = 0.
  • If the first character is '-', set sign = -1 and increment i.
  • Then convert characters to digits and update result.
  • Multiply result by sign before returning.

Illustration:

Java
// Handling Negative Numbers
class Geeks {
  
    static int myAtoi(String s) {
      
        // Handle null or empty string
        if (s == null || s.isEmpty()) {
            return 0;
        }

        int res = 0, 
        sign = 1, 
        i = 0;

        // Handle negative sign
        if (s.charAt(0) == '-') {
            sign = -1;
            i++; 
        }

        // Traverse the string
        for (; i < s.length(); i++) {
            char ch = s.charAt(i);

            // If non-numeric character, return 0
            if (ch < '0' || ch > '9') {
                return 0;
            }

            res = res * 10 + (ch - '0');
        }

        return res * sign;
    }

    public static void main(String[] args) {
        String s = "-567";
        System.out.println(myAtoi(s)); 
    }
}

Output
-567
  • Time Complexity: O(N), where N is the length of the string. We iterate through the string once to process digits.
  • Auxiliary Space: O(1), as we use constant extra space for the result, sign, and index.


Approach 3: Handling Invalid Inputs and Whitespaces

This approach handles whitespace, positive and negative signs, and stops conversion at first non-numeric character.

Steps to Implement:

  • To remove leading or trailing spaces usetrim() method.
  • Initialize result = 0, sign = 1, and i = 0.
  • If the first character is '-' or '+', update sign.
  • Then convert characters into digits until a non-digit is encountered.
  • Multiply result by sign before returning.

Illustration:

Java
// Handling Whitespaces & Invalid Characters
class Geeks {

    static int myAtoi(String s) {

        // Handle null or empty string
        if (s == null || s.isEmpty()) {
            return 0;
        }

        // Remove leading spaces
        s = s.trim();
        if (s.isEmpty()) { 
            return 0;
        }

        int res = 0, sign = 1, i = 0;

        // Handle signs
        if (s.charAt(i) == '-' || s.charAt(i) == '+') {
            sign = (s.charAt(i) == '-') ? -1 : 1;
            i++; 
        }

        // Traverse the string
        for (; i < s.length(); i++) {
            char ch = s.charAt(i);

            // Stop at first non-digit character
            if (ch < '0' || ch > '9') {
                break;
            }

            res = res * 10 + (ch - '0');
        }

        return res * sign;
    }

    public static void main(String[] args) {
        String s = "   -123xyz";
        System.out.println(myAtoi(s)); 
    }
}

Output
-123
  • Time Complexity: O(N), as we traverse the string once, skipping leading spaces and processing digits.
  • Auxiliary Space: O(1), using a constant amount of space for variables.

Approach 4: Handling Four Corner Cases

  • Discarding all leading whitespace: The leading whitespaces should be ignored, as they do not contribute to the value of the number.
  • Sign of the number: The string can have a '+' or '-' sign at the beginning to indicate whether the number is positive or negative.
  • Overflow: Integer overflow occurs if the number exceeds the range that can be represented by an integer (Integer.MAX_VALUE or Integer.MIN_VALUE). We must handle overflow situations.
  • Invalid Input: If the string contains invalid characters (non-numeric), the conversion should stop and only the valid part should be processed.

To remove the leading whitespaces run a loop until a character of the digit is reached. If the number is greater than or equal to INT_MAX/10. Then return INT_MAX if the sign is positive and return INT_MIN if the sign is negative. The other cases are handled in previous approaches. 

Dry Run: 

Below is the implementation of the above approach: 

Java
// Java program for robust implementation of atoi()
class Geeks {
    
    static int myAtoi(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }

        int i = 0, sign = 1, base = 0, n = s.length();
        int INT_MAX = Integer.MAX_VALUE, INT_MIN = Integer.MIN_VALUE;

        // Discard leading whitespaces
        while (i < n && s.charAt(i) == ' ') {
            i++;
        }

        // Check if string became empty after removing spaces
        if (i == n) 
          return 0;

        // Handle sign
        if (s.charAt(i) == '-' || s.charAt(i) == '+') {
            sign = (s.charAt(i) == '-') ? -1 : 1;
            i++;
        }

        // Convert valid numeric characters
        while (i < n && Character.isDigit(s.charAt(i))) {
            int digit = s.charAt(i) - '0';

            // Handle integer overflow before updating base
            if (base > INT_MAX / 10 || (base == INT_MAX / 10 && digit > 7)) {
                return (sign == 1) ? INT_MAX : INT_MIN;
            }

            base = base * 10 + digit;
            i++;
        }

        return base * sign;
    }


    public static void main(String[] args) {
      
        System.out.println(myAtoi("   -123"));    
        System.out.println(myAtoi("4193 with")); 
        System.out.println(myAtoi("words 987")); 
        System.out.println(myAtoi("21474836460"));
        System.out.println(myAtoi("-91283472332"));
    }
}

Output
-123
4193
0
2147483647
-2147483648
  • Time Complexity: O(n), where n is the length of the input string. We only traverse the string once.
  • Space Complexity: O(1) as we are using only a few variables and no extra space proportional to the input size.

Please refer complete article on Write your own atoi() for more details.


Similar Reads