我正在尝试下面的挑战。https://www.hackerrank.com/contests/projecteuler/challenges/euler145/submissions/code/25262675
基本上,代码需要将大约 1-19 位不同长度的数字反转,将这些数字相加,然后检查结果是否完全由奇数组成,不允许使用前导 0(例如,应排除 100)。
我精炼的代码可以计算出这些数字,但是在网站上有一个超时,我觉得它在性能方面还不够好。
我曾尝试使用正则表达式,但无法正确排序并且影响了结果。任何指导作为编写它以使其尽可能快地运行的最佳方式都会非常有帮助,无论是如果它需要使用正则表达式或其他任何东西。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long t = scan.nextInt(); //Number of numbers to test
for (int i = 1; i <= t; i++){
long n = scan.nextLong();
calc(n); //begins calculation
}
}
public static void calc(long n)
{
long reversible = 0; //Counter
for (long i = 1; i < n; i++)
{
if (i%10 != 0) //Makes sure number does not end with a zero
{
long reverse = 0;
long j = i;
long checkOdd;
//Reverse the number
while( j != 0 )
{
reverse = reverse * 10;
reverse = reverse + j%10;
j = j/10; //
}
long result = i + reverse; //Add current number and reverse
while (result != 0)
{
//Check and remove numbers to see if odd or not
checkOdd = result%10;
if (checkOdd%2 == 0){ //Even detected, move to next number
result = 0;
}
result = result/10; //Move to next digit
//Counts and ensures we do not count the same number multiple times
if (checkOdd%2 == 1 && result == 0)
{
reversible = reversible + 1;
}
}
/** REGEX TEST CODE -- fails when result is 5 digits long after testing */
/** if(Pattern.matches("\\d[^02468]", Long.toString(result)))
{
System.out.println(result);
reversible = reversible + 1;
}*/
}
}
System.out.println(reversible);
}