如何找出所有回文数字

Joe*_*Joe 10 java algorithm

回文数或数字回文是像16461是"对称的"数量,即保持相同时,其数字是相反的.

术语回文来自回文,它指的是像转子这样的词,在其字母的反转下保持不变.

第一个回文数字(十进制)是:

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, ...
Run Code Online (Sandbox Code Playgroud)

如何查找下面的所有回文数字,比如10000?

M P*_*oet 27

恢复你的推理.不要试图找到这些数字,而是创建它们.您可以简单地取任何数字并对其进行镜像(总是在长度上),对于相同的数字,只需在它们之间添加0..9(对于具有奇数长度的数字).


aio*_*obe 15

生成所有回文到特定限制.

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;
}
Run Code Online (Sandbox Code Playgroud)


测试回文性

使用字符串

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);
}
Run Code Online (Sandbox Code Playgroud)

使用整数

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;
}
Run Code Online (Sandbox Code Playgroud)