call(back)
Algorithms & Data StructureseasySign in to star problems

Parse an Integer Without parseInt

Write toInt(str): turn "1234" into 1234 without parseInt, Number or unary plus (in Python, without int() or float() on the string).

  • An optional leading - or + is allowed.
  • Anything else that isn't a digit, or a string with no digits, gives NaN (float("nan") in Python).
toInt("1234")   // 1234
toInt("-42")    // -42
toInt("12a")    // NaN

The JavaScript grader switches off parseInt and parseFloat. Hold yourself to the rest of the rules.

Hints

Hint 1

Map each digit character to its value through a lookup table and accumulate n = n * 10 + d.

Hint 2

Handle the sign first and reject everything else — including a lone sign with no digits.

Asked at