FastPrepParse a Signed Integer in Any Base

Parse a Signed Integer in Any Base

Microsoft logoMicrosoftMediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Parse text as a signed 64-bit integer in base, where the base is from 2 through 36.

Ignore leading and trailing ASCII whitespace. An optional leading + or - is allowed. Digits 0-9 represent values 0-9 and letters a-z or A-Z represent 10-35. Return the canonical decimal string, or INVALID when the base, syntax, digit, or signed 64-bit range is invalid.

Function

parseIntegerInBase(text: String, base: int) → String

Examples

Example 1

text = "  -7f "base = 16return = "-127"

7f is 127 in base 16 and the sign makes it negative.

Example 2

text = "101"base = 2return = "5"

Binary 101 equals decimal 5.

Example 3

text = "8000000000000000"base = 16return = "INVALID"

The positive value exceeds signed 64-bit range.

Constraints

  • 0 <= text.length <= 200.
  • 0 <= base <= 40; values outside 2 through 36 are invalid.
  • Whitespace is ASCII space, tab, carriage return, or newline.

More Microsoft problems

See Microsoft hiring insights
public String parseIntegerInBase(String text, int base) {
    // Write your solution here.
}
text" -7f "
base16
expected"-127"
Checking account…