Reading a number from text
Turn the digits at the start of a string into a whole number, carefully. About 10 minutes.
Reading a number the way you would aloud
A form field arrives as text: " -42 apples". The computer sees characters, not a number. You have to build the number yourself, the same way you read "42" aloud: 4, then 4 tens and 2.
For each digit, multiply what you have so far by 10 and add the new digit. The digit's value is its character code minus the code for "0". So "42" goes 0, then 4, then 42.
- sign
- 1
- value
- 0
Skip the spaces at the front.
Real input is messy
Users type spaces first, add a plus or minus sign, follow the number with words, or type no digits at all. Handle each in order: skip the spaces, read an optional sign, read digits, and stop at the first character that isn't a digit.
And numbers can be too big. If it goes past what a 32-bit number holds, return the nearest limit instead of letting it overflow.
i, n, sign, value = 0, len(s), 1, 0
while i < n and s[i] == " ":
i += 1
if i < n and s[i] in "+-":
sign = -1 if s[i] == "-" else 1
i += 1
while i < n and s[i].isdigit():
value = value * 10 + int(s[i])
i += 1
value *= sign
return max(-2**31, min(2**31 - 1, value))What does " -12abc" read as?
- A−12
- B0
- C12
Show the answer
−12. Skip the spaces, read the minus, read 1 and 2, stop at the a.
Read a number
Read a whole number from the start of a string. Skip leading spaces, then read an optional + or −, then as many digits as follow. Ignore everything after them. If there are no digits, return 0. If the number is outside −2,147,483,648 to 2,147,483,647, return the nearest end of that range.
s = " -42 apples" → -42
0 ≤ length ≤ 200 · printable ASCII characters