
Problem
Solution
Submissions
String to Integer
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to implement the string-to-integer conversion function (similar to C's atoi function). The function should convert a string to a 32-bit signed integer, handling whitespace, optional signs, and invalid characters while respecting integer overflow limits.
Example 1
- Input: s = "42"
- Output: 42
- Explanation:
- The string "42" contains only valid digits.
- No leading whitespace or sign to handle.
- Parse digits 4 and 2 to form number 42.
- 42 is within 32-bit integer range. Return 42.
- The string "42" contains only valid digits.
Example 2
- Input: s = " -42"
- Output: -42
- Explanation:
- The string " -42" starts with whitespace.
- Skip leading whitespace to get "-42".
- Detect negative sign and parse digits 4, 2.
- Form number -42 which is within valid range.
- Return -42.
- The string " -42" starts with whitespace.
Constraints
- 0 ≤ s.length ≤ 200
- s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'
- Handle integer overflow by clamping to [-2³¹, 2³¹ - 1]
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Skip leading whitespace characters first
- Check for optional sign (+ or -) and store the sign
- Parse digits one by one until non-digit character is encountered
- Handle integer overflow by checking bounds before multiplication
- Return 0 if no valid conversion can be performed
- Clamp result to 32-bit signed integer range