Implement the myAtoi(string s)
function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s)
is as follows:
" "
).'-'
or '+'
, assuming positivity if neither present.[-231, 231 - 1]
, then round the integer to remain in the range. Specifically, integers less than -231
should be rounded to -231
, and integers greater than 231 - 1
should be rounded to 231 - 1
.Return the integer as the final result.
Example 1:
Input: s = "42"
Output: 42
Explanation:
The underlined characters are what is read in and the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) ^
Example 2:
Input: s = " -042"
Output: -42
Explanation:
Step 1: " -042" (leading whitespace is read and ignored) ^ Step 2: " -042" ('-' is read, so the result should be negative) ^ Step 3: " -042" ("042" is read in, leading zeros ignored in the result) ^
Example 3:
Input: s = "1337c0d3"
Output: 1337
Explanation:
Step 1: "1337c0d3" (no characters read because there is no leading whitespace) ^ Step 2: "1337c0d3" (no characters read because there is neither a '-' nor '+') ^ Step 3: "1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit) ^
Example 4:
Input: s = "0-1"
Output: 0
Explanation:
Step 1: "0-1" (no characters read because there is no leading whitespace) ^ Step 2: "0-1" (no characters read because there is neither a '-' nor '+') ^ Step 3: "0-1" ("0" is read in; reading stops because the next character is a non-digit) ^
Example 5:
Input: s = "words and 987"
Output: 0
Explanation:
Reading stops at the first non-digit character 'w'.
Constraints:
0 <= s.length <= 200
s
consists of English letters (lower-case and upper-case), digits (0-9
), ' '
, '+'
, '-'
, and '.'
.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach involves examining the input string character by character and converting it to an integer if possible. We go through the string validating each character to determine if it can be part of an integer. We will handle all the edge cases step by step to meet the requirements.
Here's how the algorithm would work step-by-step:
def string_to_integer_atoi(input_string):
string_index = 0
string_length = len(input_string)
# Remove leading whitespaces
while string_index < string_length and input_string[string_index] == ' ':
string_index += 1
sign = 1
if string_index < string_length:
# Determine the sign
if input_string[string_index] == '+':
string_index += 1
elif input_string[string_index] == '-':
sign = -1
string_index += 1
result = 0
while string_index < string_length and input_string[string_index].isdigit():
digit = int(input_string[string_index])
# Check for overflow before multiplying
if result > (2**31 - 1) // 10 or (result == (2**31 - 1) // 10 and digit > 7):
if sign == 1:
return 2**31 - 1
else:
return -2**31
result = result * 10 + digit
string_index += 1
# Apply the sign
result = sign * result
# Clamp the result to the 32-bit signed integer range
if result > 2**31 - 1:
return 2**31 - 1
if result < -2**31:
return -2**31
return result
This problem asks us to convert a string into an integer. The optimal approach carefully parses the string, handling edge cases and potential errors along the way to avoid unnecessary calculations and ensure accuracy.
Here's how the algorithm would work step-by-step:
def string_to_integer_atoi(input_string):
string_index = 0
string_length = len(input_string)
# Remove leading whitespace.
while string_index < string_length and input_string[string_index] == ' ':
string_index += 1
sign = 1
# Determine the sign of the number.
if string_index < string_length and (input_string[string_index] == '+' or input_string[string_index] == '-'):
sign = -1 if input_string[string_index] == '-' else 1
string_index += 1
integer_result = 0
# Convert digits to an integer.
while string_index < string_length and input_string[string_index].isdigit():
digit = int(input_string[string_index])
# Check for potential overflow before updating result
if integer_result > (2**31 - 1) // 10 or (integer_result == (2**31 - 1) // 10 and digit > 7):
return 2**31 - 1 if sign == 1 else -2**31
if integer_result < (-2)**31 // 10 or (integer_result == (-2)**31 // 10 and digit < -8):
return 2**31 - 1 if sign == 1 else -2**31
integer_result = integer_result * 10 + digit
string_index += 1
# Apply the sign.
return sign * integer_result
Case | How to Handle |
---|---|
Null or empty input string | Return 0 if the input string is null or empty. |
String contains only whitespace characters | Return 0 if after trimming the string consists only of whitespace. |
String starts with a non-numeric and non-sign character | Return 0 if the first non-whitespace character is not a digit or a sign (+/-). |
Multiple sign characters at the beginning | Consider only the first valid sign character and ignore subsequent ones, potentially returning 0 if they alternate signs. |
Integer overflow (positive) | Clamp the result to Integer.MAX_VALUE if the parsed integer exceeds the maximum positive 32-bit signed integer value. |
Integer underflow (negative) | Clamp the result to Integer.MIN_VALUE if the parsed integer is less than the minimum negative 32-bit signed integer value. |
String contains non-numeric characters after a valid integer | Stop parsing at the first non-numeric character after the optional sign and valid digits. |
Leading zeros before significant digits | The leading zeros should be skipped during conversion but are still valid. |