
Problem
Solution
Submissions
String to Integer
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C program to implement the myAtoi(string) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The function should handle leading whitespaces, optional sign, and convert digits until a non-digit character is encountered or the end of string is reached.
Example 1
- Input: s = "42"
- Output: 42
- Explanation: No leading whitespace. No sign, so positive. Read digits "42". Convert to integer 42.
Example 2
- Input: s = " -42"
- Output: -42
- Explanation: Skip leading whitespaces. Read negative sign. Read digits "42". Apply negative sign to get -42.
Constraints
- 0 ≤ s.length ≤ 200
- s consists of English letters, digits, space ' ', '+', and '-'
- Return 0 if no valid conversion can be performed
- Clamp the result to 32-bit signed integer range [-2^31, 2^31 - 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 all leading whitespace characters
- Check for optional sign (+ or -)
- Read digits and build the result number
- Stop reading when non-digit character is encountered
- Handle integer overflow by checking before multiplication
- Return 0 for invalid input or if no digits are found