Skip to content

8 : String to Integer (atoi) #173

@ayushHardeniya

Description

@ayushHardeniya

Problem Number

8

Problem Title

String to Integer (atoi)

LeetCode Link

https://leetcode.com/problems/string-to-integer-atoi/description/

Contribution Checklist

  • I have written the Approach section.
  • I have written the Intuition section.
  • I have included a working C++ solution.
  • I will raise a PR and ensure the filename follows the convention [Number]. [Problem Title].cpp.

Approach

  1. Skip Extra Spaces:

    First, move through the string and ignore all spaces at the beginning.
    We only start reading when we find a number or a sign (+ or -).

Image
  1. Check the Sign:
Image
  • If the next character is '-', we mark the number as negative.
  • If it’s '+', we keep it as positive.
  • Then, move to the next character.
  1. Read the Digits:
Image
  • Go through each character while it’s a number ('0''9').
  • Convert it to an integer using s[i] - '0'.
  • Add it to our result using ans = ans * 10 + digit.
  1. Check for Overflow / Underflow:
Image
  • If the number becomes bigger than INT_MAX (2³¹ − 1), stop and return INT_MAX.
  • If it becomes smaller than INT_MIN (−2³¹), return INT_MIN.
    This keeps the value within the valid integer range.
  1. Return the Final Number:
    Multiply the result by the sign (+1 or -1) and return it.

Time Complexity: O(n) - we go through the string once.
Space Complexity: O(1).

Intuition

This problem works like the C function atoi(), where we convert a string into an integer manually.

Note : atoi stands for ASCII to Integer

We simply:

  • Skip all spaces at the start.
  • Check if there’s a + or - sign..
  • Read the digits one by one until a non-digit appears.
  • Stop if the number goes beyond the integer range.

The idea is to build the number step by step, just like how a program reads and converts text into numbers.

Solution in C++

class Solution {
public:
    int myAtoi(string s) {
        int l = s.length();
        int sign = 1, i = 0;
        long long ans = 0;

        // trimming leading spaces
        while (i < l && s[i] == ' ') i++;
        

        // sign check condition
        if (i == l)
            return 0;
        if (s[i] == '-') {
            sign = -1;
            i++;
        } else if (s[i] == '+')
            i++;

        // converting characters to integer
        while (i < l && isdigit(s[i])) {
            int digit = s[i] - '0';
            ans = ans * 10 + digit;

            // overflow condition handling
            if (sign == 1 && ans > INT_MAX) {
                return INT_MAX;
            }
            if (sign == -1 && (-1 * ans) < INT_MIN) {
                return INT_MIN;
            }
            i++;
        }

        return (int)(ans * sign);
    }
};

Metadata

Metadata

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions