Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Math Exercises: Reverse an integer number

Java Math Exercises: Exercise-6 with Solution

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.

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.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe