Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out all palindromic numbers

Tags:

java

algorithm

A palindromic number or numeral palindrome is a "symmetrical" number like 16461, that remains the same when its digits are reversed.

The term palindromic is derived from palindrome, which refers to a word like rotor that remains unchanged under reversal of its letters.

The first palindromic numbers (in decimal) are:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22,
33, 44, 55, 66, 77, 88, 99, 101, 111,
121, 131, 141, 151, 161, 171, 181,
191, ...

How to find out all palindromic numbers below, say, 10000?

like image 485
Joe Avatar asked Jun 19 '11 08:06

Joe


2 Answers

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).

like image 99
M Platvoet Avatar answered Sep 20 '22 11:09

M Platvoet


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;
}
like image 45
aioobe Avatar answered Sep 18 '22 11:09

aioobe