Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

reversing an integer with overflow handled

// Java program to reverse digits
// of a number
public class GFG
{
 
  static int reversDigits(int num)
  {
    int rev = 0  ;
 
    while(num != 0){       
      int rem = num % 10 ;
      num /= 10 ;
 
      if(rev > Integer.MAX_VALUE/10 || rev == Integer.MAX_VALUE/10 && rem > 7){
        return 0 ;
      }
 
      if(rev < Integer.MIN_VALUE/10 || rev == Integer.MIN_VALUE/10 && rem < -8){
        return 0 ;
      }
 
      rev = rev*10 + rem ;
    }
 
    return rev ;
  }
 
  // Driver code
  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) );
  }
}
 
// This code is contributed by jana_sayantan.
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #reversing #integer #overflow #handled
ADD COMMENT
Topic
Name
9+8 =