[Solved] Palindrome

• October 14th, 2013, 01:58 PM
satyarlenka
[Solved] Palindrome
It has been a few weeks for me in Java. Yesterday I was trying to write a program to check if a given number is palindrome or not. I was able to write a program in which it asks the user to input the number of digits. It ran okay without any errors.
Code Java:

```public class PalindromeNumberCheck {   public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Enter the number to be checked : "); Scanner input = new Scanner(System.in); int num = input.nextInt(); int numOriginal = num; System.out.println("Enter the number of digits : "); int n = input.nextInt(); int reverse = 0; while(n != 0) { reverse = reverse + (num%10) * (int)Math.pow(10,(n-1)); num = num / 10 ; n--; } System.out.println("reverse = "+reverse); if(reverse == numOriginal) System.out.println("The number is a palindrome !"); else System.out.println("The number is not a palindrome !"); }   }```
My question is, Is there any other way to do it without asking the user to input the number of digits? Kindly someone point out the logic and I will try out to write the program by myself.
• October 14th, 2013, 02:14 PM
GregBrannon
Re: [HELP] Palindrome
You mean you want to use the program's logic to figure out how many digits the user entered, right?

There are a number of ways. The simplest that occurs to me is to first accept the number as a String using input.nextLine(), then use a String method to determine its length, then parse the String object to an integer using Integer.parseInt( inputString ).

If there are elements of that suggestion you can't or won't use for whatever reason, then you could divide the number entered as an int by 10 in a loop until the value is < 10 and use a counter to determine how many digits it has.

Will either of those suggestions work for you?
• October 14th, 2013, 02:23 PM
satyarlenka
Re: [HELP] Palindrome
Thanks Greg!! :) Oh my god. That's easy. It never really stuck my mind. Especially the second one.(facepalm)