String to Integer (atoi)
Try to solve the String to Integer problem.
We'll cover the following
Statement#
Write a function, myAtoi(string s), that converts a string to a 32–bit signed integer. It is equivalent to the atoi function in C/C++.
The myAtoi function reads the input string, s, from left to right for the conversion process. The conversion begins by removing any leading whitespace. Then, it checks if the next character is '+' or '-'. If it's '-', it implies that the result is negative, and there must be a '-' sign in front of the resulting integer. Otherwise, '+' implies that the result is positive, so there is no need to add a '+' sign in front of the resulting integer. For example, "-
After removing the whitespace, if the first non-space character is not a sign character, '+' or '-', but a non-digit character, i.e., an English letter or the period '
The function continues to read the string while checking if the subsequent character is a digit and stops reading when a non-digit character is encountered. For characters that are digits, the function concatenates them. Next, it transforms the collected digits into their corresponding integer value. It ensures that the sign value, if any, is adjusted to the resulting integer. For example, "
Finally, the function checks if the resulting integer goes out of the range of a 32–bit signed integer,
Note: The space character (' ') and the period ('
') are part of the non-digit characters. Therefore, they will get ignored and won't affect the final answer. For example, " " converts to and " " converts to .
Constraints:
s.lengthThe string
smay have:digit characters from
– . non-digit characters, including lower-case and upper-case English letters, space character (' '), period ('
'), and sign characters ('+' and '-').
Examples#
1 of 5
2 of 5
3 of 5
4 of 5
5 of 5
Understand the problem#
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
String to Integer (atoi)
What is the output if the following string is given as input?
= " you Rock"
“”
" you rock"
Figure it out!#
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself#
Implement your solution in the following coding playground.
Solution: Add Binary
Solution: String to Integer (atoi)