You are given a 32-bit signed integer ‘N’. So, the integer will lie in the range [-2^31, 2^31 - 1]. Your task is to return the reverse of the given integer. If reversing causes overflow, then return -1.
Note:
(1) Do not use data types with the capacity of more than 32-bit like ‘long int’ or ‘long long int’ in C++. The problem is meant to reverse the integer using a 32-bit data type only.
(2) You should assume that the environment does not allow storing signed or unsigned 64-bit integers.
Input Format:
The first line of input contains an integer 'T' representing the number of test cases.
The first and the only line of each test case contains a 32-bit signed integer ‘N’ representing the integer to be reversed.
Output Format:
For each test case, return the reverse of integer, ’N’.
The output of each test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 5
-2^31 <= N <= 2^31 - 1
Time limit: 1 sec
2
8596396
1253489646
6936958
-1
In test case 1, Given ‘N’ = 8596396
On reversing the digits of ‘N’, we will get 6936958. So the output is 6936958.
In test case 2, Given ‘N’ = 1253489646
On reversing the digits of ‘N’, we will get 6469843521 which is greater than 2^31 - 1. Thus, it will cause an overflow. So the output is -1.
2
-803
-1
-308
-1
In test case 1, Given ‘N’ = -803
On reversing the digits of ‘N’, we will get -308. So the output is -308.
In test case 2, Given ‘N’ = -1
On reversing the digits of ‘N’, we will get -1. So the output is -1.
Can you exploit the fact that the given number is a 32 bit signed integer?
The idea is to use the fact that the input ‘N’ is a 32 bit signed integer. So, as mentioned, -2147483648 <= ‘N’ <= 2147483647. In this range, for ‘N’ = 10 * x + y, the ‘N’ can never attain a value when |x| = INT_MAX / 10, y = 8 or 9 for x > 0 and y = -9, for x < 0.
Therefore, it is sufficient to check |x| > INT_MAX / 10 (i.e. x > INT_MAX / 10 or x < INT_MIN / 10) for overflow.
The steps are as follows:
O(log | N |), Where ‘N’ is the 32-bit signed integer.
Since number ‘N’ has approximately log|N| digits. Since we are dividing the integer ‘N’ in each iteration of the while loop, the while loop will execute log|N| times. Thus the time complexity will be O(log | N |).
O(1).
Since no auxiliary space has been used to perform the reversal. Thus the space complexity will be O(1).