Reverse Integer in java

Reverse Integer in java

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 – 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Input Format

The first line of input contains the integer n.

Output Format

Print the integer n in reverse if it lies within the range, else print 0.

Example 1

Input

321

Output

123

Example 2

Input

-321

Output

-123

Example 3

Input

120

Output

21

###Constraints

-2^31 <= x <= 2^31 – 1

Solution of Reverse Integer in java:–

import java.util.*;
import java.lang.*;
import java.io.*;
 
public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc= new Scanner(System.in);
        int n= sc.nextInt();
        int num = n;
 
        int curr_digit=0, rev_num=0, pre_rev_num=0;
 
        while(num!=0){
 
          curr_digit= num%10;
          rev_num= (rev_num*10) + curr_digit;
 
          if((rev_num-curr_digit)/10 != pre_rev_num) {    
            // check overflow condition
            // rev_num can go out of MAX_Int range
            // it will give garbage value after max range
            // condition becomes true
 
            System.out.println(0);
            return;
          }
 
          pre_rev_num= rev_num;
          num/=10;
          
        }
      System.out.println(rev_num);
	}
}

Add a Comment

Your email address will not be published. Required fields are marked *