我编写了一个程序来计算 2 个三位数的最大回文乘积。我已经在 Project Euler 解决了这个问题,但是在 HackerRank 中解决同样的问题在一些测试用例中失败了。我想知道出了什么问题。
输入:
第一行包含 T,表示测试用例的数量。接下来是 T 行,每行包含一个整数 N。
约束:
1≤T≤100
101101<N<1000000
public class Solution {
static boolean isPalin ( int i){
int low = 0;
String a = String.valueOf(i);
int high = a.length() - 1;
while(low<high){
if(a.charAt(low) == a.charAt(high)){
low++;
high--;
}else{
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int noOfCases = in.nextInt();
int currMax = 0, result = 0;
int no_one, no_two;
int largest = -1;
for(int i=0; i<noOfCases; i++){
currMax = in.nextInt();
for(no_one = 100; no_one<=999; no_one++){
for(no_two = 101; no_two<=999; no_two++){
result = no_one * no_two;
if(isPalin(result)){
if(result > largest && result < currMax )
largest = result;
}
}
}
System.out.println(largest);
}
}
最佳答案
您正在测试多个案例,但只在程序开始时将 largest 重置为 -1。
尝试将 largest=-1;
添加到循环 i 的开头。
关于java - 最大回文积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33464563/