欧拉计划第4题

原题:
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.

中文大意:
一个回文数是从两头读都相同。由两个两位数相乘产生的最大回文数是9009,9009 = 91*99。
求有两个三位数相乘产生的最大回文数。

我的代码:public class MyClass {

public static void main(String args[]) {
    int result;//保存乘积结果
    String s;//保存转换的字符串
    boolean ifPalindrome;//确定是否为回文
    for(int i = 990;i <= 999;i++){
        for(int k = 100;k <=999;k++){
            ifPalindrome =true;//初始设定为真
            result = i*k;
            s = Integer.toString(result);
            for(int j = 0;j < s.length()/2;j++){
                if(s.charAt(j)!=s.charAt(s.length()-j-1)){
                    ifPalindrome = false;//找到了不是回文的数
                    break;//中端内循环
                }
            }
            if(ifPalindrome == true)
                System.out.println(result);//如果为回文则打印
        }
    }

}

}

因为是求最大的回文数,我们可以将一个数的值设置稍大点,但如果你直接设置为999可能就找不到所求的值。具体思路是将乘积结果转换为字符串,然后通过字符串的首尾比较来确定是否为回文,算法比较简单。
但最后还是需要从打印的结果中找出最大的值,可以用排序算法将值排序。本人略懒,便略过此步骤。
最后的结果为906609 = 993*913

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值