Ctrl K

Lenient Number Reader

Medium
Sensors report readings as a string raw, and they are sloppy about it: there may be extra spaces, unit suffixes and other junk. Pull an integer off the front of the string using these rules: 1. Skip every space ' ' at the start of the string. 2. If the next character is '-' or '+', read it as the sign. With no sign, the number is positive. At most one sign is allowed. 3. Read consecutive digits until a non-digit shows up or the string ends. Leading zeros don't change the value. If no digits were read at all, the result is 0. 4. The result has to fit a 32-bit signed integer: if it is below −2³¹, return −2³¹; if it is above 2³¹ − 1, return 2³¹ − 1. Anything after the digits is ignored. Return the number you read.
Example 1
raw='   +0075 kg' → 75

Leading spaces are skipped, the "+" is read, then the digits "0075" give 75; reading stops at the space.

Example 2
raw='-99999999999 m' → -2147483648

The number is below −2³¹, so the answer is pinned to the lower bound −2147483648.

Example 3
raw='v2.5' → 0

The first meaningful character is the letter "v", neither a digit nor a sign, so no number is read and the answer is 0.

Constraints
  • 0 ≤ len(raw) ≤ 200
  • raw consists of English letters (lowercase and uppercase), digits, spaces and the characters +, -, .
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Repeat-Free Stretch MediumLongest Mirror Fragment MediumReading a Zigzag by Rows MediumNumber in Roman Numerals MediumKeypad Words Medium
loading Python…
Input
raw='   +0075 kg'
Expected
75

Run checks the first 3 tests in your browser. Submit checks all 187 tests on the server, hidden ones included.