1

I'm a beginner in programming. Can you please tell me what's wrong with my code? The code shows not palindrome, although the number is a palindrome.

public static void main(String[] args) {
    // TODO code application logic here
    Scanner in = new Scanner(System.in);
    int a =0;
    int n =in.nextInt();
    while(n >0){
        int temp =n %10;
        a = a*10+temp;
        n = n/10;
    }
    System.out.println(a);
    if( n ==a){
        System.out.println("The number is palindrome");
    }else{
        System.out.println("The number is not palindrome");
    }
}

Output:

16461
16461
The number is not palindrome
ggorlen
  • 44,755
  • 7
  • 76
  • 106
gouri panda
  • 312
  • 2
  • 11
  • Because at the end of the loop, `n = 0`. The condition of the `while` loop ensures that *(ignoring user entering a negative number)*. – Andreas Apr 20 '19 at 16:58
  • What about numbers, which end in a zero? Should 0123210 be a palindrome? Your approach says no. – derpirscher Apr 20 '19 at 17:06
  • @derpirscher Since it's looking for *numerical* palindromes, `123210` is not a palindrome, since numbers don't have leading zeroes. – Andreas Apr 20 '19 at 17:19
  • 1
    Possible duplicate of [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Max Vollmer Apr 20 '19 at 17:58

1 Answers1

1

Your code works, except for the fact that you are not keeping the original value intact to compare it with the reversed number you compute. This works for your input value by saving a copy of your original input, and using that at the end to compare with what you compute:

public static void main(String[] args) {
    // TODO code application logic here
    Scanner in = new Scanner(System.in);
    int a = 0;
    int n = in.nextInt();
    int orign = n;
    while(n >0){
        int temp = n %10;
        a = a*10+temp;
        n = n/10;
    }
    System.out.println(a);
    if( orign == a){
        System.out.println("The number is palindrome");
    }else{
        System.out.println("The number is not palindrome");
    }
}

Sample sessions:

16461
16461
The number is palindrome

12345
54321
The number is not palindrome

3
3
The number is palindrome
CryptoFool
  • 21,719
  • 5
  • 26
  • 44