LeetCode 7: Reverse Integer Solution
Master LeetCode problem 7 (Reverse Integer), 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.
7. Reverse Integer
Problem Explanation
Explanation
To reverse an integer, we can use the following steps:
- Initialize a variable
reversed
to store the reversed number. - Handle negative numbers by checking if the input is negative and then multiplying the reversed number by -1 at the end.
- Iterate through each digit of the input number by continuously dividing it by 10 and extracting the last digit.
- Multiply the current
reversed
number by 10 and add the extracted digit to the ones place. - Check for overflow by comparing the new
reversed
number with the integer limits. - Return the final
reversed
number.
The time complexity of this approach is O(log(x)) where x is the input number, as we iterate through the digits of the number. The space complexity is O(1) as we only use a constant amount of extra space.
Solution Code
class Solution {
public int reverse(int x) {
int reversed = 0;
while (x != 0) {
int digit = x % 10;
x /= 10;
if (reversed > Integer.MAX_VALUE / 10 || (reversed == Integer.MAX_VALUE / 10 && digit > 7)) return 0;
if (reversed < Integer.MIN_VALUE / 10 || (reversed == Integer.MIN_VALUE / 10 && digit < -8)) return 0;
reversed = reversed * 10 + digit;
}
return reversed;
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 7 (Reverse Integer)?
This page provides optimized solutions for LeetCode problem 7 (Reverse Integer) 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 7 (Reverse Integer)?
The time complexity for LeetCode 7 (Reverse Integer) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 7 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 7 in Java, C++, or Python.