Parse an Integer From Text
MediumStrings243 tests
You get a string text. Read an integer from it, using these steps in order:
- Skip any space characters (
' ') at the start. Only the space character counts here. - If the next character is
'+'or'-', read it as the sign. Read at most one sign. If there is no sign, the number is positive. - Read digits (
0to9) until you reach a character that is not a digit, or the end of the string. Ignore everything after that. - If you read no digits, the result is
0. Leading zeros are allowed ("007"gives7). - Keep the result inside the 32-bit signed range
[-2147483648, 2147483647]. If the number is smaller, return-2147483648. If it is bigger, return2147483647.
Return the integer.
Note
Do not use a built-in function that does all of this for you. A digit string can be much longer than 10 characters, so check the limits as you read each digit.
Examples
Example 1
- Input:
- " -305xyz"
- Output:
- -305
Skip the three spaces, read the minus sign, read the digits 305, and stop at the letter x.
Example 2
- Input:
- "word 42"
- Output:
- 0
The first character is a letter, not a space, sign or digit. No digits are read, so the result is 0.
Example 3
- Input:
- "9876543210"
- Output:
- 2147483647
The number is bigger than 2147483647, so the result is clamped to 2147483647.
Constraints
0 <= text.length <= 30textcontains only English letters, digits,' ','+','-'and'.'.
Run checks your code against the 3 examples. Submit checks it against all 243 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.