DSA Factory
Free Strings lessonsStrings · Stage 4 · Parsing · Step 1

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.

Each new digit: times 10 so far, plus the digit.
s = " -42 apples" (␣ is a space)
␣
0
␣
1
␣
2
-
3
4
4
2
5
␣
6
a
7
p
8
p
9
l
10
e
11
s
12
i
sign
1
value
0

Skip the spaces at the front.

Move 1 of 5

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.

In order: spaces, then a sign, then digits.
Too big? clamp to the 32-bit limits.
In code
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))
Quick check

What does " -12abc" read as?

  1. A−12
  2. B0
  3. C12
Show the answer

−12. Skip the spaces, read the minus, read 1 and 2, stop at the a.

Your problem

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.

Example
s = "   -42 apples" → -42

0 ≤ length ≤ 200 · printable ASCII characters

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve