Write a function myAtoi(string s) that turns a string into a 32-bit signed integer, like the atoi function of the C language. Follow these steps:
- Skip all spaces at the start of the string.
- Look at the next character. If it is
'-', the number is negative. If it is '+', the number is positive. Take this sign character. If there is no sign, the number is positive.
- Read digits one by one. Stop at the first character that is not a digit, or at the end of the string. Ignore everything after that.
- Turn the digits into a number and apply the sign. If you did not read any digit, the number is 0.
- The result must fit in the 32-bit signed range [-2^31, 2^31 - 1]. If it is smaller than -2^31, return -2^31. If it is bigger than 2^31 - 1, return 2^31 - 1.
- Return the result.
Examples
Example 1:
Input: s = " -17abc"
Output: -17
Explanation: Skip the space at the start, take the sign -, read 17, and stop at the letter a.
Example 2:
Input: s = "words 55"
Output: 0
Explanation: The first character after the spaces is a letter, so no digit is read and the result is 0.
Example 3:
Input: s = "99999999999"
Output: 2147483647
Explanation: The number is too big, so it is cut down to 2^31 - 1.