Algorithm for Reversing an Int in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class PalindromeNumbers {
 
	public static void main(String[] args) {
		int number;
		Scanner kb = new Scanner(System.in);
 
		System.out.println("Enter a number: ");
		number = kb.nextInt();
 
		if(isPalindrome(number)) 
			System.out.println(number+" is palindrome!");
		else
			System.out.println(number+" is not palindrome!");		
 
	}
	//reverse the number
	public static int reverse(int num) {
		int reverse = 0;
		while(num > 0) {
			reverse = reverse * 10 + num % 10;
			num /= 10;
		}
		return reverse;		
	}
 
	//check whether number is palindrome or not
	public static boolean isPalindrome(int num) {
		return num == reverse(num);		
	}
}
Share This!

Leave a Reply

Your email address will not be published.