8. String to Integer

8. String to Integer #

Problem Statement #

Implement 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:

Read in and ignore any leading whitespace.
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.
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.
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).
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.
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. 

Approach #

Let’s break the problem into simple pieces and try to handle each piece.

Initial Processing #

  1. Skip leading whitespaces.
  2. Identify the sign (positive or negative).
  3. Handle leading + or - only once, as any subsequent symbols are considered extraneous.

Overflow Prevention #

  1. Implement a check for potential overflow:
    • If n exceeds INT_MAX/10, it would lead to overflow.
    • If n equals INT_MAX/10, additional digits are allowed only up to 7 to avoid overflow.

Iterative Parsing #

  1. Iterate through the input until a non-digit character is encountered.

Code: #

#include <bits/stdc++.h>
using namespace std;

int a = 1e9+7;
class Solution {
public:
    int myAtoi(string s) {
        int i= 0; 
        while(s[i]==32) i+=1;
        int sign = 1;
        if(s[i]=='-'){ sign *= -1;i+=1;}
        else if(s[i]=='+')i+=1;
        int num = 0;
        while(i<s.size() and isdigit(s[i])){
            if(num>INT_MAX/10 or (num==INT_MAX/10 and (s[i]-'0')>7))
            return sign==1?INT_MAX:INT_MIN;
            else{
                num = num*10+(s[i]-'0');
            }
            i+=1;
        }
        return num*sign;
    }
};

Time Complexity #

O(n)- where n is the length of the input string s.

Space Complexity #

O(1)- constant space, as only the variables are used and don’t scale to the size of the input.

Thanks! Have a nice day!!😉