Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Implement atoi: skip leading spaces, read an optional sign and digits, stop at the first non-digit, clamp to 32-bit range.

Problem: Implement atoi: skip leading spaces, read an optional sign and digits, stop at the first non-digit, clamp to 32-bit range.
def atoi(s):
    s = s.lstrip(); sign, i, n = 1, 0, 0
    if s[:1] in '+-' and s: sign = -1 if s[0] == '-' else 1; i = 1
    while i < len(s) and s[i].isdigit():
        n = n * 10 + int(s[i]); i += 1
    return max(-2**31, min(2**31 - 1, sign * n))
print(atoi("   -42abc"), atoi("4193 with words"), atoi("words 987"), atoi("-91283472332"))
What is printed?
  1. A. -42 4193 987 -2147483648
  2. B. 42 4193 0 -2147483648
  3. C. -42 4193 0 -2147483648
  4. D. -42 4193 0 -91283472332

Correct answer: C. -42 4193 0 -2147483648

Parsing stops at the first non-digit; text before any digit gives 0 ("words 987" → 0). Values beyond 32 bits are clamped to INT_MIN / INT_MAX. In C++/Java the overflow check must happen before n·10 + d. O(n).

More Coding Interview Problems questions

Exams that ask this topic