Python Program To Write Your Own atoi()

We are given a string that may represent a number and need to convert it into an integer using Python. The atoi() function is used in C programming to convert a string parameter into an integer value if the string is a valid integer, otherwise it shows undefined behavior.

Sample Examples

Input 1

string S = "9834"

Output

9834

Explanation: The string represents a valid number, so we get the same output as an integer.

Input 2

string S = "09 uy56"

Output

Invalid Input

Explanation: The string contains whitespaces and characters, making it invalid.

Input 3

string str = "-987"

Output

-987

Method 1: Assuming Valid Input String

In this approach, we assume the string is valid and contains only digits with an optional minus sign for negative numbers. We'll create a function that processes the string character by character ?

def atoi(string):
    # Check for negative number
    neg = 1
    if string[0] == '-':
        neg = -1
    
    ans = 0
    i = 0
    
    # If negative, start from index 1
    if neg == -1:
        i = 1
    
    # Process each digit
    while i < len(string):
        cur = int(string[i])
        ans = ans * 10 + cur
        i += 1
    
    return ans * neg

# Test the function
string = "-354663"
result = atoi(string)
print("The value of the current number is:", result)
The value of the current number is: -354663

How It Works

The algorithm multiplies the current result by 10 and adds the new digit. For example, processing "123": 0 ? 1 ? 12 ? 123.

Method 2: Handling Invalid Input Strings

This approach validates the input string and handles invalid characters. We use the ord() function to check ASCII values ?

def atoi_with_validation(string):
    # Check for negative number
    neg = 1
    if string[0] == '-':
        neg = -1
    
    ans = 0
    i = 0
    
    # If negative, start from index 1
    if neg == -1:
        i = 1
    
    while i < len(string):
        # Check if current character is a digit
        if ord(string[i]) > ord('9') or ord(string[i]) < ord('0'):
            return "Invalid Input"
        
        cur = int(string[i])
        ans = ans * 10 + cur
        i += 1
    
    return ans * neg

# Test with valid input
string1 = "12345"
result1 = atoi_with_validation(string1)
print("Result for '12345':", result1)

# Test with invalid input
string2 = "-354 663"
result2 = atoi_with_validation(string2)
print("Result for '-354 663':", result2)
Result for '12345': 12345
Result for '-354 663': Invalid Input

Comparison

Method Input Validation Time Complexity Space Complexity
Method 1 No O(N) O(1)
Method 2 Yes O(N) O(1)

Key Points

  • Use ord() to get ASCII values for character validation
  • Handle negative numbers by checking the first character
  • Build the number by multiplying by 10 and adding each digit
  • Return appropriate error messages for invalid input

Conclusion

We've implemented a custom atoi() function that converts string representations of numbers to integers. Use Method 1 for trusted input or Method 2 when input validation is required.

Updated on: 2026-03-27T07:32:15+05:30

630 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements