Project Euler - 4

本文探讨了如何通过两层循环遍历3位数,找到其乘积形成的最大回文数字,详细介绍了算法实现过程及关键步骤。

problem :

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers  is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.
 题目意思是 两个2位数相乘最大的回文数字式9009 = 91*99;那么求出两个3位数相乘最大的回文数字


solution:

使用两层循环,从999开始依次获得i和j的乘积,加入到arraylist中,最后找出最大的回文数字。这里需要注意,虽然是从最大的数开始 遍历,但是找到的第一个回文数字不一定是最大的。

public class Problem4 {
    private static ArrayList<Integer> nums;
    
    public static void main(String[] args){
        boolean flag = true;
        nums = new ArrayList<Integer>();
        for (int i = 999; i >= 100 && flag; i--) {
            for (int j = 999; j >= 100 && flag; j--) {
                if (checkPalindromic(Integer.toString(i * j))) {
                    //System.out.printf("%d=%d*%d\n", i * j, i, j);
                    nums.add(i*j);
                }
            }
        }
        System.out.println("max="+getMax(nums));
        
    }
    
    // 判断是否是回文
    public static boolean checkPalindromic(String n){
        if (n == null || n.length() < 1) {
            return false;
        }
        
        int len = n.length();
        
        for (int i = 0; i < (len / 2); i++) {
            if (n.charAt(i) != n.charAt(len - i - 1)) {
                return false;
            }
        }
        return true;
    }
    
    // 获取arraylist中最大的数
    public static int getMax(ArrayList<Integer> arr) {
        int max = arr.get(0);
        for (int i = 1; i < arr.size(); i++) {
            if (arr.get(i) > max)
                max = arr.get(i);
        }
        return max;
    }
    
    
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值