FastPrepString to Integer (atoi)

String to Integer (atoi)

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Convert s to a signed 32-bit integer.

  1. Skip leading ASCII space characters.
  2. Read one optional + or - sign.
  3. Consume the longest following prefix of decimal digits. If no digit is consumed, return 0.
  4. Ignore every character after that digit prefix.
  5. Clamp a value below -2^31 to -2^31 and a value above 2^31 - 1 to 2^31 - 1.

Function

stringToInteger(s: String) → int

Examples

Example 1

s = "123"return = 123

All characters belong to the decimal digit prefix.

Example 2

s = "   -042xyz"return = -42

Leading spaces and the negative sign are consumed. Parsing stops before x.

Example 3

s = "91283472332"return = 2147483647

The parsed positive value exceeds the signed 32-bit maximum and is clamped.

Constraints

  • 0 <= s.length <= 200.
  • s may contain ASCII letters, digits, spaces, signs, and punctuation.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int stringToInteger(String s) {
    // Write your code here.
}
s"123"
expected123
Checking account…