How to find out all palindromic numbers

后端 未结 8 1849
独厮守ぢ
独厮守ぢ 2020-12-14 12:05

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 derive

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 12:29

    Generating all palindromes up to a specific limit.

    public static Set allPalindromic(int limit) {
    
        Set result = new HashSet();
    
        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;
    }
    

提交回复
热议问题