Reverse Integer

Posted: 18 Mar, 2021
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

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.
Constraints:
1 <= T <= 5
-2^31 <= N <= 2^31 - 1   

Time limit: 1 sec
Approach 1

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:

 

  • Declare an integer variable, ‘RESULT’, and initialized it to zero, to store the reversed value of ‘N’.
  • Run a loop while ‘N’ is not zero.
    • Extract the last digit of ‘N’ and store it in an integer variable, ‘LASTDIGIT’.
    • Check for overflow. If ‘RESULT’ is greater than INT_MAX / 10’ or ‘RESULT’ is less than INT_MIN / 10’ that shows that appending the ‘LASTDIGIT’ to the ‘RESULT’ will cause an overflow. So, return -1.
    • Else, append the ‘lastDigit’ to the ‘RESULT’.
    • Divide ‘N’ by 10 to remove the last digit.
  • Return the ‘RESULT’.
Try Problem