Given a 32-bit integer N. The task is to reverse N, if the reversed integer overflows, print -1 as the output.
Examples
Input: N = 123
Output: 321
Input: N = -123
Output: -321
Input: N = 120
Output: 21
Approach: Unlike approaches Set 1 of the article, this problem can be solved simply by using a 64-bit data structure and range of int data type [-2^31, 2^31 - 1]
- Copy the value of the given number N in a long variable
- Check if it is negative
- Now reverse the long number digit by digit, and if at any step, its value goes out of range the int type, return 0.
- Make the resultant number negative if the given number is negative
- Again check for the number to be in int range. If yes return 0, else return the reversed number.
Below is the implementation of the above approach.
OutputReverse of no. is 6985
Time Complexity: O(D), where D is the number of digits in N.
Auxiliary Space: O(1)
Another Approach:
- Define a function "reverse" that takes an integer "n" as input.
- Initialize a variable "rev" to 0 to store the reversed integer.
- Iterate through each digit of the input integer by dividing it by 10 until it becomes 0.
- In each iteration, find the remainder of the input integer when divided by 10, which gives the current digit.
- Check if the current value of "rev" will cause an overflow or underflow when multiplied by 10 and added to the current digit.
- If it will cause an overflow or underflow, return -1 to indicate that the reversed integer has overflowed.
- Otherwise, multiply the current value of "rev" by 10 and add the current digit to it to reverse the integer.
- After reversing the integer, print the value of "rev".
Below is the implementation of the above approach:
Time Complexity: The reverse() function iterates through each digit of the input integer n, so the time complexity of the function is O(log n), where n is the magnitude of the input integer.
Auxiliary Space: The space complexity is O(1)