String to Integer (atoi) LeetCode Solution

Difficulty Level Medium
Frequently asked in Adobe Amazon Apple Bloomberg Cisco Facebook Goldman Sachs Google Intel LinkedIn Microsoft PayPal Qualcomm SAP Uber VMware
RedfinViews 7133

Problem Statement

The String to Integer (atoi) Leetcode Solution -“String to Integer (atoi)” states that Implementing the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi function).

The algorithm for myAtoi(string s) is as follows:

  1. Read in and ignore any leading whitespace.
  2. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
  3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
  4. Convert these digits into an integer (i.e. "123" -> 123"0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
  5. If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
  6. Return the integer as the final result.

Note:

  • Only the space character ' ' is considered a whitespace character.
  • Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.

Example:

String to Integer (atoi) LeetCode Solution

Approach

Idea:

The main idea is to iterate the string until we get the first digit part of the string or we traversed the whole string (i.e index goes out of bound).

So, first, we traverse and ignore leading whitespace’s then check for positive or negative signs if no sign character is present in the string then by default we take the digit is positive.

And finally, we traverse until our character is in the range of int and we will end our loop when we get a character other than digit or digit goes beyond the Integer range.

Remember if digit >=INT_MAX then we return INT_MAX or if digit <=INT_MIN then we return INT_MIN.

Code

C++ Program of String to Integer (atoi)

class Solution {
public:
    int myAtoi(string s) {
        int result=0;     // helper variables
        int i=0;
        int sign=1;
    
        while(i<s.size()&&s[i]==' ')i++;  //ignore leading white space
        
        if(s[i]=='-'||s[i]=='+')          //check if number positve or negative
        {
            sign=s[i]=='-'?-1:1;
            i++;
        }
        // now iterate across digits if any
    // should only be in range 0-9
        while(i<s.length()&&(s[i]>='0'&&s[i]<='9'))  //traverse string till nondigit not found or string ends
        {
            int digit=(s[i]-'0')*sign;
            if(sign==1 && (result>INT_MAX/10 || (result==INT_MAX/10 && digit>INT_MAX%10))) return INT_MAX; //check for overflow
            if(sign==-1 &&(result<INT_MIN/10 || (result==INT_MIN/10 && digit<INT_MIN%10))) return INT_MIN; //check for underflow
            
            result=result*10+digit; // update result
            i++;
        }
    return result;
    }
};

Java Program of String to Integer (atoi)

class Solution {
    public int myAtoi(String s) {
        int result=0;    // helper variables
        int i=0;
        int sign=1;
    
        while(i<s.length()&&s.charAt(i)==' ')i++;  //ignore leading white space
        if(i==s.length())return 0;
        if(s.charAt(i)=='-'||s.charAt(i)=='+')          //check if number positve or negative
        {
            sign=s.charAt(i)=='-'?-1:1;
            i++;
        }
        // now iterate across digits if any
    // should only be in range 0-9
        while(i<s.length()&&(s.charAt(i)>='0'&&s.charAt(i)<='9'))  //traverse string till nondigit not found or string ends
        {
            int digit=(s.charAt(i)-'0')*sign;
            if(sign==1 && (result>Integer.MAX_VALUE/10 || (result==Integer.MAX_VALUE/10 && digit>Integer.MAX_VALUE%10))) return Integer.MAX_VALUE; //check for overflow
            if(sign==-1 &&(result<Integer.MIN_VALUE/10 || (result==Integer.MIN_VALUE/10 && digit<Integer.MIN_VALUE%10))) return Integer.MIN_VALUE; //check for underflow
            
            result=result*10+digit; // update result
            i++;
        }
    
    return result;
    }
}

Complexity Analysis for String to Integer (atoi) LeetCode Solution

Time complexity: O(N) because we are traversing each character in the input at most once and for each character we spend a constant amount of time.

Space complexity: O(1) because we used constant space to store the sign and the result.

Translate »