Parse a Signed 32-Bit Integer From Untrusted Text
Last updated: November 29, 2026
Quick Overview
Implement a function like C's atoi that reads an integer from the start of a string: skip leading spaces, accept an optional sign, read digits until the first non-digit, and clamp results that overflow the signed 32-bit range.
Microsoft
November 29, 20260
0
0 solved
Implement a function like C's atoi that reads an integer from the start of a string: skip leading spaces, accept an optional sign, read digits until the first non-digit, and clamp results that overflow the signed 32-bit range.
Microsoft has asked variations of string-to-integer parsing for decades because Windows and Office are full of C and C++ code where an unchecked overflow is a security bug. The interviewer cares less about the happy path and more about whether you detect overflow before it happens and enumerate edge cases unprompted.
What the Interviewer Expects
- Lists the grammar explicitly before coding
- Detects overflow before multiplying, without relying on big integers
- Handles the asymmetric range where -2147483648 is valid but 2147483648 is not
- Stops at the first invalid character and returns 0 for no digits
- Writes a compact table of test cases
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you report errors instead of silently returning 0?
- Extend it to parse hexadecimal with an 0x prefix.
- Why is checking overflow after the multiply undefined behavior in C?
- How would you parse a 64-bit value on a platform without 64-bit arithmetic?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Grammar: optional spaces, optional + or -, then digits; anything after the digits is ignored. No digits gives 0. Values outside [-2^31, 2^31 - 1] clamp to the nearest bound. I will not use Pytho...
High-Level Design
A small left-to-right state machine: whitespace, sign, digits. The only subtle part is overflow. In C, value * 10 + digit can overflow before you can compare it, so the comparison must be rearranged...