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;
}
}