How to find out all palindromic numbers

There is a brute force approach, that you loop through all the numbers and check whether they are palindrome or not. To check, reverse the number and compare. Complexity should be O(n log10(n)). [ Not that log10() matters, but for sake of completeness. ]

Other one is to, generate palindromes according to number of digits. Lets say you have to generate 5 digit palindromes, they are of the form ABCBA, so just loop through 0-9 and fill all the positions. Now, if you have generate palindromes below 10^4, then generate palindromes of 1,2,3 and 4 digits.

I wrote quick(and dirty) C++ codes to test the speed of both the algorithms (8 digit palindrome). Brute force : Ideone. (3.4s) Better algorithm : Ideone. (0s)

I have removed print statements, because Ideone doesn't allow this large data in output.

On my computer the times are :

Brute force:
real    0m7.150s
user    0m7.052s
Better algorithm:
real    0m0.024s
user    0m0.012s

I know that you have mentioned language as Java, but i don't know Java and these codes simply show you the difference between the algorithms, and you can write your own Java code.

PS: I have tested my code for 8 digit palindromes with brute force, can't be sure if it produces wrong for above 8 digits, though the approach used is general. Also, i would have liked to give the links to code in comments, as correct approach is already mentioned, but i don't have required privileges.


Revert your reasoning. Not try to find these numbers but instead create them. You can simply take any number and mirror it (which is always even in length) and for that same number simply add 0..9 in between (for the numbers with odd length).


Generating all palindromes up to a specific limit.

public static Set<Integer> allPalindromic(int limit) {

    Set<Integer> result = new HashSet<Integer>();

    for (int i = 0; i <= 9 && i <= limit; i++)
        result.add(i);

    boolean cont = true;
    for (int i = 1; cont; i++) {
        StringBuffer rev = new StringBuffer("" + i).reverse();
        cont = false;
        for (String d : ",0,1,2,3,4,5,6,7,8,9".split(",")) {
            int n = Integer.parseInt("" + i + d + rev);
            if (n <= limit) {
                cont = true;
                result.add(n);
            }
        }
    }

    return result;
}


Testing for palindromicity

Using Strings

public static boolean isPalindromic(String s, int i, int j) {
    return j - i < 1 || s.charAt(i) == s.charAt(j) && isPalindromic(s,i+1,j-1);
}

public static boolean isPalindromic(int i) {
    String s = "" + i;
    return isPalindromic(s, 0, s.length() - 1);
}

Using integers

public static boolean isPalindromic(int i) {
    int len = (int) Math.ceil(Math.log10(i+1));
    for (int n = 0; n < len / 2; n++)
        if ((i / (int) Math.pow(10, n)) % 10 !=
            (i / (int) Math.pow(10, len - n - 1)) % 10)
            return false;
    return true;
}

Tags:

Algorithm

Java