找到由两个3位数字的乘积制成的最大回文。 (JAVA)

我在解决Project Euler问题4时遇到了一些麻烦。我对编程缺乏经验,并没有真正理解其他答案。 我设法写了一个代码,打印所有六位数的回文。 如何找到由两个3位数字相乘得出的最大回文数?

public class Main { public static void main(String[] args) { int num = 998001; int count=0; int temp1, temp2, temp3, temp4, temp5, temp6; int temp; int num1=999; int num2=100; for (int i = 100000; i <= 998001; i++) { num=998001-count; temp=num; temp1=temp%10; temp=temp/10; temp2=temp%10; temp=temp/10; temp3=temp%10; temp=temp/10; temp4=temp%10; temp=temp/10; temp5=temp%10; temp=temp/10; temp6=temp%10; temp=temp/10; if (temp1==temp6 && temp5==temp2 && temp3==temp4) { System.out.println(num); } count=count+1; } } } 

这是一个循环遍历1-999的所有数字并将它们与1-999中所有可能数字相乘的方法。 您需要定义一个方法isPalindrome(int) ,它将检查给定的int是否是回文。

 //save the largest number int largest = 0; //loop over every possible product of numbers from 100-999 for (int i = 999; i >= 100; i--) { for (int j = i; j >= 100; j--) { int curr = i * j; //if the current number is a palindrome and is greater than the last found largest if (isPalindrome(curr) && curr > largest) { //save it as the new largest found number largest = curr; } } } 

isPalindrome方法可能如下所示:

 private static boolean isPalindrome(Integer possible) { String toStr = possible.toString(); int len = toStr.length(); if (len % 2 == 1) { len = len - 1; } for (int i = 0; i < len / 2; i++) { if (toStr.charAt(i) != toStr.charAt(toStr.length() - (1 + i))) { return false; } } return true; } 

对于3位数循环,可以从100到1000(不包括)开始。

你可以尝试这个::

 int num1 = 0, num2 = 0; for(int i=100; i<1000; i++){ for(int j=100; j<1000; j++){ String mul = String.valueOf(i*j); if(isPalindrome(mul)){ num1 = i; num2 = j; } } } System.out.println(num1*num2); 

实施回文方法:

 boolean isPalindrome(String str) { String strRev = new StringBuilder(str).reverse().toString(); return str.equals(strRev); } 

这很好但是把它当作参考并根据需要改进谢谢

下面是一个代码来检查PALINDROME ,而不将其转换为String

 bool checkPalindrome(int n) { int num = n; int s = 0; while(num!=0) { s = s*10 + (num%10); num = num/10; } if(s==n) return true; return false; } 

正如你可以看到,如果n = 120 ,则反向计算为s = 21而不是021 ,但这没关系,记住回文数不会以0结尾,因为如果确实如此,那么它会有从0开始,这使它成为无效的数字!!!!

希望这可以帮助!!!

以下是我对同一问题的看法……

创建列表更容易,我们知道将从最小到最大填充,因为计数器只有rize ……

  List palindrome = new ArrayList<>(); // create integer list for ( int i = 900; i<999; i++){ for ( int j = 900; j < 950; j++){ // both counter numbers are bigger than 900 // because there will those two int's be, logically String newMul = String.valueOf(i * j); // make it string for palindrome comparation String strRev = new StringBuilder(newMul).reverse().toString(); // rotate previous string // for palindrome comparation if(newMul.equals(strRev)){ //if its equal palindrome.add(i * j); //will put multiplication result of i and j into list } } } System.out.println(palindrome.get(palindrome.size()-1)); // last number in list is the } // biggest so lets print it out 

基本上,如果它是一个回文,你只需要很少的铸造,但如果它是,只需乘以i和j将它们放入列表......它将循环很长一段时间,但是这样你检查了所有更大的数字最大的回文比900多...

希望我帮忙......