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:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics