您的位置:首页 > 其它

欧拉计划第4题

2016-07-12 12:38 232 查看
原题:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: