题目4:找出由两个三位数乘积构成的回文。

一个回文数指的是从左向右和从右向左读都一样的数字。最大的由两个两位数乘积构成的回文数是9009 = 91 * 99.

找出最大的有由个三位数乘积构成的回文数。

 

原题目链接:Problem 4


还是不能暴力算,因为是求最大的回文数,所以从最大的开始减


public class Problem4 {

    public static void main(String[] args) {

        int res = countPalindromic();
        System.out.println(res);

    }


    public static int countPalindromic() {
        int min = 100001;
        int max = 999999;

        int res = 0;
        int value = 0;

        for (int a = 999; a > 100; a--) {

            for (int b = max / a; b > 100; b--) {

                if(b > 999)
                    continue;

                value = a * b;

                if (value > max || value < min)
                    break;

                if (isPalindromic(value) && value > res) {
                    res = value;
                    System.out.println("value:" + value + ",a:" + a + ",b:" + b);
                }

            }

        }

        return res;
    }


    public static Boolean isPalindromic(int value) {
        String a = String.valueOf(value);
        String b = new StringBuffer(a).reverse().toString();
        return a.equals(b);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章