找到由两个3位数字的乘积制成的最大回文。 (JAVA) [英] Find the largest palindrome made from the product of two 3-digit numbers. (Java)
问题描述
我在解决Project Euler问题4时遇到了一些麻烦。我对编程缺乏经验,并没有真正理解其他答案。我设法写了一个代码,打印所有六位数的回文。如何找到由两个3位数字相乘得出的最大回文?
I am having a bit of trouble solving Project Euler question 4. I am inexperienced in programming and didn't really understand other answers. I managed to write a code that prints all six-digits palindromes. How do I find the largest palindrome made from the multiplying of two 3-digit numbers?
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是否是回文。
Here is a method which loops over all numbers from 1-999 and multiplies them with all possible numbers from 1-999. You will need to define a method isPalindrome(int)
that will check if a given int is a palindrome.
//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位数字的乘积制成的最大回文。 (JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!