Reputation: 1
I'm trying to make a java code that displays the largest palindrome number made from the product of two 3-digit numbers. It outputs all palindromes, not in numerical order. I don't know why. Please help! Here's my code:
`class Scratch { public static void main(String[] args) { int dig1, dig2, dig3, dig4, dig5, dig6, product;
for (int i =999; i>100; i--){
for (int j =999; j>=i;j--){
product = j*i;
dig1= product/100000;
dig2= (product/10000)%10;
dig3= (product/1000)%10;
dig4= (product/100)%10;
dig5= (product/10)%10;
dig6= (product%10);
if ((dig1==dig6) && (dig2==dig5) && (dig3==dig4)){
System.out.println((product));
break;
}
}
}
}}
Upvotes: 0
Views: 182
Reputation: 1
//Here is the simple solution
public class Test {
public static void main(String[] args) throws Exception{
int x=4547454;
int temp=x;
String s="";
while(temp>0){
s=s+temp%10;
temp=temp/10;
}
System.out.println(s);
if(Integer.valueOf(s) == x)
System.out.println("palindrome");
else
System.out.println("not palindrome");
}
}
Upvotes: 0
Reputation: 40057
A couple suggestions.
for (int i = 999; i > 100; i--) {
for (int k = i; k > 100; k--) {
val
is the product of i
and j
.int rev = 0;
int temp = val;
while (temp != 0) {
rev = rev * 10 + temp % 10;
temp /= 10;
}
then
if (rev == val) { is a palindrome?
...
}
As each number is found, you can find the largest as follows. At the start,
initialize max
to Integer.MIN_VALUE. Then do the following:
int savei = 0;
int savej = 0;
int max = Integer.MIN_VALUE;
// then later as you find the palindromes.
if (max < val) {
max = val;
savei = i
savej = j;
}
At the end, you will have the largest palindrome and the three digit numbers that divide it.
Upvotes: 1