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:

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

Approaches

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…