DIY: String to Integer (atoi)
Solve the interview question "String to Integer (atoi)", in this lesson.
We'll cover the following
Problem statement
In this coding exercise, you are given a string. You have to convert this string to a 32-bit signed integer. The string may have a leading whitespace. The first non-whitespace character in the string may or may not be numeric.
-
If it isn’t numeric, it may be a
+
or-
sign, which will determine if the final result is negative or positive, respectively. You can assume that the result will be positive if neither is present. -
If it is numeric, you will read the next characters until the next non-digit character appears or the end of the string is reached. Then, you will convert these digits into an integer.
-
If the first non-whitespace character in the string is neither numeric nor a
+
or-
sign, then you should convert the string to0
.
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 characters after the digits.
- A string consists of English letters (lowercase and uppercase), digits (
0-9
),' '
,'+'
,'-'
, and'.'
.
Input
The input will be a string. The following are some example inputs to the function:
# Sample Input 1
"123"
# Sample Input 2
" -123"
# Sample Input 3
"9612 with words"
# Sample Input 4
"words and 345"
# Sample Input 5
"-93283472332"
Output
For the input given above, the output will be:
# Sample Output 1
123
# Sample Output 2
-123
# Sample Output 3
9612
# Sample Output 4
0
# Sample Output 5
-2147483648
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.