Reverse digits of an integer

Write a program to reverse an integer assuming that the input is a 32-bit integer. If the reversed integer overflows, print -1 as the output.

// Java program to reverse a number

class GFG

{

/* Iterative function to reverse

digits of num*/

static int reversDigits( int num)

{

int rev_num = 0 ;

while (num > 0 )

{

rev_num = rev_num * 10 + num % 10 ;

num = num / 10 ;

}

return rev_num;

}

// Driver code

public static void main (String[] args)

{

int num = 4562 ;

System.out.println( "Reverse of no. is "

+ reversDigits(num));

}

}

// This code is contributed by Anant Agarwal.

Output:

6985

However, if the number is large such that the reverse overflows, the output is some garbage value. If we run the code above with input as any large number say 1000000045, then the output is some garbage value like 1105032705 or any other garbage value.

How to handle overflow?
The idea is to store previous value of the sum can be stored in a variable which can be checked every time to see if the reverse overflowed or not.
Below is the implementation to deal with such a situation.

// Java program to reverse digits of a number

class ReverseDigits

{

/* Iterative function to reverse digits of num*/

static int reversDigits( int num)

{

// Handling negative numbers

boolean negativeFlag = false ;

if (num < 0 )

{

negativeFlag = true ;

num = -num ;

}

int prev_rev_num = 0 , rev_num = 0 ;

while (num != 0 )

{

int curr_digit = num% 10 ;

rev_num = (rev_num* 10 ) + curr_digit;

// checking if the reverse overflowed or not.

// The values of (rev_num - curr_digit)/10 and

// prev_rev_num must be same if there was no

// problem.

if ((rev_num - curr_digit)/ 10 != prev_rev_num)

{

System.out.println( "WARNING OVERFLOWED!!!" );

return 0 ;

}

prev_rev_num = rev_num;

num = num/ 10 ;

}

return (negativeFlag == true )? -rev_num : rev_num;

}

public static void main (String[] args)

{

int num = 12345 ;

System.out.println( "Reverse of no. is " + reversDigits(num));

num = 1000000045 ;

System.out.println( "Reverse of no. is " + reversDigits(num));

}

}

Output:

Reverse of no. is 54321 WARNING OVERFLOWED!!! Reverse of no. is 0