0

This code gets an integer n and displays all palindrome numbers less than n. But seems the for loop doesn't work; because when I enter a number except 0, 1 and negatives, nothing happens. I tried debugging, but couldn't find the problem!

Sample input: 30

Sample output: 1 2 3 4 5 6 7 8 9 11 22

import java.util.Scanner;

public class PalindromeNumbers {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        if (n == 0 || n == 1 || n < 0)
            System.out.println("There's no Palindrome Number!");
        else {
            for (int num = 1; num < n; num++) {
                int reversedNum = 0;
                int temp = 0;
                while (num > 0) {

                    // use modulus operator to strip off the last digit
                    temp = num % 10;

                    // create the reversed number
                    reversedNum = reversedNum * 10 + temp;
                    num = num / 10;

                }
                if (reversedNum == num)
                    System.out.println(num);
            }
        }
    }
}
Community
  • 1
  • 1
Aura
  • 61
  • 1
  • 1
  • 5

3 Answers3

2

You run into an infinite loop: you use num in your for loop as an index, and reset it to 0 inside the loop. Use different variables, and it should work!

for (int i = 1; i < n; i++) {
    int num = i;

    ...

    if (reversedNum == i)
        System.out.println(i);
}
Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44
1

You are changing your num variable inside your for loop. The next time num < n is executed, the value changed (to 0). Try something like this:

for (int num = 1; num < n; num++) {
   int reversedNum = 0;
   int temp = 0;
   int temp2 = num;
   while (temp2 > 0) {

       // use modulus operator to strip off the last digit
       temp = temp2 % 10;

       // create the reversed number
       reversedNum = reversedNum * 10 + temp;
       temp2 = temp2 / 10;

   }
   if (reversedNum == num)
       System.out.println(num);
}

This way, you use a temp variable to calculate your reversedNum, and still keeps the value of num for the next loop iteration.

Marcelo
  • 1,471
  • 3
  • 19
  • 22
1

You can do it in a more concise way:

public static void main(final String args[]) {
    final Scanner input = new Scanner(System.in);
    final int max = input.nextInt();
    if (max <= 0) {
        System.out.println("There's no Palindrome Number!");
    } else {
        for (int i = 1; i < max; i++) {
            if (isPalindrome(i)) {
                System.out.println(i);
            }
        }
    }
}

private static boolean isPalindrome(final int num) {
    final String temp = "" + num;
    return new StringBuilder(temp).reverse().toString().equals(temp);
}