w3resource

Java: Reverse an integer number


Reverse an Integer

Write a Java program to reverse an integer number.

Sample Solution:

Java Code:

public class Example6 {
   public static void main(String[] args) {
	int num =1287;   
	int is_positive = 1;
        if (num < 0) {
            is_positive = -1;
            num = -1 * num;
        }
        int sum  = 0;
        while (num > 0) {
            int r = num % 10;
            
            int maxDiff = Integer.MAX_VALUE - sum * 10;
            if (sum > Integer.MAX_VALUE / 10 || r > maxDiff) 
				System.out.println("Wrong number");;
            
            sum = sum * 10 + r;
            num /= 10;
        }
        System.out.println(is_positive * sum);
   }
}

Sample Output:

7821

Flowchart:

Flowchart: Reverse an integer number.

For more Practice: Solve these Related Problems:

  • Write a Java program to reverse an integer without converting it to a string, using arithmetic operations.
  • Write a Java program to reverse an integer recursively and then verify if it is a palindrome.
  • Write a Java program to reverse an integer by iteratively extracting its digits with modulus and division.
  • Write a Java program to reverse an integer and compare the reversed value with the original to determine symmetry.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to count the absolute distinct value in an array.
Next: Write a Java program to convert Roman number to an integer number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.