String to Integer (atoi)
Advanced String Algorithms DSA practice problem on Onlearn.
Difficulty: medium.
Topics: Implement Atoi, String Manipulation, Loops, Conditional Statements, Range Checking, Data Types, Input/Output Operations, string processing, string manipulation, error handling, type conversion, input validation, String to Integer (atoi).
Convert String to Integer (atoi) Implement the atoi function, which converts a string to a 32 bit signed integer. The function should behave as follows: 1. Read and Discard Leading Whitespace : The function first discards as many whitespace characters (only ' ') as necessary until the first non whitespace character is found. 2. Check for Sign : Then, it checks if the next character is ' ' or '+'. If it is, this determines the sign of the integer. If not, a positive sign is assumed. 3. Read Digits : The function then reads as many numerical digits as possible until the first non digit character or the end of the input string is reached. 4. Convert to Integer : The numerical digits are converted into an integer. 5. Handle Overflow : If the integer exceeds the range of a 32 bit signed integer [ 2^31, 2^31 1], then INT MAX (2147483647) or INT MIN ( 2147483648) should be returned appropriately. 6. Handle Invalid Input : If no valid conversion could be performed (e.g., the first non whitespace character is not a digit or a sign, or the string is empty/only whitespace), return 0. Note: Only the space character ' ' is considered a whitespace character. Do not consider any other characters as whitespace. Input Specification A single string s consisting of English letters, digits, spaces, '+', ' ', and '.'. The length of s will be between 0 and 200 characters, inclusive. Output Specification Return the converted 32 bit signed integer. Constraints 0 <= s.length <= 200 s consists of English letters (lower case and upper case), digits (0 9), ' ', '+', ' ', and '.'. The return value must be within the range [ 2^31, 2^31 1]. That is, [ 2147483648, 2147483647]. Sample Test Cases Sample Input 1: Sample Output 1: Explanation 1: The string "42" is converted to the integer 42. Sample Input 2: Sample Output 2: Explanation 2: Leading whitespace is skipped. The ' ' sign is read, and then the digits "42" are read and converted. The result is 42. Sample Input 3: Sample Output 3: Explanation 3: The digits "4193" are read until the non digit character ' ' is encountered. The rest of the string is ignored. The result is 4193. Sample Input 4: Sample Output 4: Explanation 4: The first non whitespace character is 'w', which is not a digit or a sign. Therefore, no valid conversion can be performed, and 0 is returned. Sample Input 5: Sample Output 5: Explanation 5: The number " 91283472332" is outside the range of a 32 bit signed integer. Since it's less than INT MIN, INT MIN is returned.