我正在尝试编写一个程序,可以在开始元素和结束元素之间找到素数列表和快乐数字列表。它似乎在大多数情况下都有效,但有 2 个特定的测试用例由于某种原因无法通过,尽管它通过了所有其他测试用例。我添加了下面的代码。
它的工作原理是取一个数字作为 startElement,然后取另一个数字作为 endElement。然后它继续返回 2 个字符串,一个包含这两个数字之间的所有素数的列表(如果有的话),另一个包含这两个数字之间的所有快乐数字的列表(如果有的话)。
一个快乐的数字是当一个数字中每个数字的平方和最终达到 1 时。例如 28。
2^2 + 8^2 = 68
6^2 + 8^2 = 100
1^2 + 0 + 0 = 1
如果这个过程最终使数字等于 4,那么这不是一个快乐的数字。
```
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int a, b;
Scanner scanner = new Scanner(System.in);
a = Integer.parseInt(scanner.nextLine());
b = Integer.parseInt(scanner.nextLine());
ChildOne childOne = new ChildOne(a, b);
ChildTwo childTwo = new ChildTwo(a, b);
//System.out.println(a);
//System.out.println(b);
System.out.println(childOne.filter());
System.out.println(childTwo.filter());
}
}
class Parent{
public int startElement;
public int endElement;
String filter(){
return null;
}
}
class ChildOne extends Parent{
ChildOne(int a, int b){
this.startElement = a;
this.endElement = b;
}
public boolean isPrime(int num){
if(num == 1)
return false;
for(int i = 2; i <= num / 2; i++){
if(num % i == 0){
return false;
}
}
return true;
}
@Override
String filter(){
String result = "";
for(int i = startElement; i <= endElement; i++){
if(isPrime(i)){
result += (" " + i);
}
}
if(result.isEmpty()){
return result;
}
return result.substring(1);
}
}
class ChildTwo extends Parent{
ChildTwo(int a, int b){
this.startElement = a;
this.endElement = b;
}
public boolean isHappy(int num){
int check = squareSum(num);
while(true){
check = squareSum(check);
//System.out.println(check);
if(check == 1)
return true;
else if(check == 4)
return false;
}
}
public int squareSum(int num){
// Gets the individual digits of the number
char[] digits = String.valueOf(num).toCharArray();
int result = 0;
for(int i = 0; i < digits.length; i++){
result += (Character.getNumericValue(digits[i]) * Character.getNumericValue((int)digits[i]));
}
return result;
}
@Override
String filter(){
String result = "";
for(int i = startElement; i < endElement; i++){
if(isHappy(i)){
result += (" " + i);
}
}
if(result.isEmpty()){
return result;
}
return result.substring(1);
}
}
```
失败的 2 个测试用例是以下 startElement 和 endElement 组
1, 5555
and
623, 3456
郑重声明,据我所知,程序在这两个测试用例中运行得很好,但该网站仍然说它失败了,我不知道为什么,因为它不会告诉我输出是什么应该是。
有人知道为什么这两个测试用例失败而所有其他测试用例似乎都通过了吗?
希望您已经找到解决方案。 这是问题所在 在 ChildTwo 中,条件应该是 i <= endElement