目标是找到两个三位数的乘积,并且是一个回文的最大数。我用java写了下面的代码,但是当我运行它的时候,我没有得到任何输出。会出什么问题呢?
public class Problem4{
public static void main(String[] args){
int reversedProduct=0;
int temp=0;
int product;
for (int a=100; a<1000; ++a){
for (int b=100; b<1000; ++b){
product=a*b;
while (product>0){
temp = product%10;
reversedProduct=reversedProduct*10+temp;
product=product/10;
} if (reversedProduct==product){
System.out.println(product);
}
}
}
}
}发布于 2012-05-20 07:28:51
在颠倒它的过程中,您正在将product置零。你应该复制一份,并将反转的产品与之进行比较。
int orig = product;
while (product>0){
temp = product%10;
reversedProduct=reversedProduct*10+temp;
product=product/10;
}
if (reversedProduct==orig){
System.out.println(reversedProduct);
}注意,在这一点上,您的解决方案将打印所有回文,而不仅仅是滞后的回文。然而,获得最大的一个应该是微不足道的。
https://stackoverflow.com/questions/10669599
复制相似问题