7. Reverse Integer
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.
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;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.