LeetCode 8: String to Integer (atoi) Solution
Master LeetCode problem 8 (String to Integer (atoi)), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
8. String to Integer (atoi)
Problem Explanation
Explanation:
To solve this problem, we need to follow the steps outlined in the problem description: ignoring leading whitespace, determining sign, converting the integer, and handling rounding. We can achieve this by iterating over the characters in the string and updating our result accordingly.
- Trim leading whitespace.
- Determine sign.
- Convert the integer value.
- Handle rounding for out-of-range values.
Time Complexity: O(n) where n is the length of the input string. Space Complexity: O(1)
:
Solution Code
class Solution {
public int myAtoi(String s) {
if (s.isEmpty()) return 0;
int i = 0, sign = 1, result = 0;
while (i < s.length() && s.charAt(i) == ' ') {
i++;
}
if (i < s.length() && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
sign = (s.charAt(i) == '-') ? -1 : 1;
i++;
}
while (i < s.length() && Character.isDigit(s.charAt(i))) {
int digit = s.charAt(i) - '0';
if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)) {
return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
result = result * 10 + digit;
i++;
}
return result * sign;
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 8 (String to Integer (atoi))?
This page provides optimized solutions for LeetCode problem 8 (String to Integer (atoi)) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 8 (String to Integer (atoi))?
The time complexity for LeetCode 8 (String to Integer (atoi)) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 8 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 8 in Java, C++, or Python.