String to Integer (atoi)
Medium · Strings · String
Problem
Implement myAtoi(s), which turns a string into a signed 32-bit integer the way C’s atoi does. Read s from the left and apply these rules in order:
- Spaces: skip any leading spaces. Only the space character " " counts.
- Sign: if the next character is - or +, read it. There is at most one sign; without one, the number is positive.
- Digits: read digits until the first character that is not a digit, or the end. Leading zeros are fine and count for nothing. If no digit was read, the result is 0.
- Range: if the number is below -2147483648 (−2^31), return -2147483648; if it is above 2147483647 (2^31 − 1), return 2147483647.
Everything after the digits is ignored, so "1337c0d3" is 1337. But the order is strict: "+-12", "words 987" and " - 1" are all 0, because something other than a digit comes where the digits should start.
As in Reverse Integer, assume only 32-bit integers can be stored. Clamp while reading, as soon as the next digit would pass the limit, instead of building a long number and clamping it at the end.
Examples
Input: s = " -042" Output: -42
The spaces are skipped, the minus is read, and 042 is 42: the leading zero counts for nothing.
Input: s = "-91283472332" Output: -2147483648
The number is below the smallest 32-bit value, so it is clamped to -2147483648.
Constraints
- 0 <= len(s) <= 200
- s consists of English letters (either case), digits, spaces, "+", "-" and "."
Approaches
- Regular expression, then clamp at the end — time O(n), space O(n)
Related problems
Start free on Cariara · Coding problems · System design studio