โ† Goldman Sachs questions

Custom parseInt Implementation in Java

Filed under Goldman Sachs

Free read 2 of 3

Trim whitespace and identify the sign of the number.

The question

Implement a function that converts a string representation of an integer into its numerical value without using built-in parsing functions like Integer.parseInt().

Constraints

  • Handle negative numbers
  • Handle leading/trailing whitespace
  • Handle potential overflow (return max/min int)
  • Input string may contain non-digit characters

Examples

Input
"123"
Output
123
Why
Standard positive integer conversion.
Input
"-456"
Output
-456
Why
Handles negative sign prefix.

Approach

  1. Trim whitespace and identify the sign of the number.

Solution

O(N) time, O(1) space

Python
def custom_parse_int(s):
    s = s.strip(); sign = 1
    if s[0] == '-': sign = -1; s = s[1:]
    res = 0
    for char in s:
        res = res * 10 + (ord(char) - ord('0'))
    return res * sign

Tips

  • What they are testing: Test for empty strings, null values, and values exceeding Integer.MAX_VALUE.
  • Common mistake: Failing to check for overflow before multiplying by 10 and adding the next digit.

Related Goldman Sachs questions

Collected from public candidate posts and coding forums. Updated Nov 2026.