给定一个字符串,我必须找到字符串中每个字符的 ASCII。如果任何 ASCII 不是素数,则必须将其转换为最接近的素数 ASCII。如果两个素数 ASCII 与原始 ASCII 等距,则取较小的。在上述操作之后,我需要将生成的 ASCII 转换为字符串。
但是我的代码的问题是它不能打印 y form ASCII 121
请帮我找出错误;提前致谢
int T = s.nextInt();
int len;
byte lowerPrime, greaterPrime, temp;
String word;
byte[] b;
for (int i = 0; i < T; i++) {
len = s.nextInt();
s.nextLine();
word = s.nextLine();
b = word.getBytes(StandardCharsets.US_ASCII);
for (int k = 0; k < b.length; k++) {
temp = b[k];
if (!checkPrime(temp)) {
lowerPrime = findPrimeSmaller(temp);
greaterPrime = findPrimeGreater(temp);
if ((temp - lowerPrime) == (greaterPrime - temp)) {
b[k] = lowerPrime;
} else if ((temp - lowerPrime) < (greaterPrime - temp)) {
b[k] = lowerPrime;
} else if ((temp - lowerPrime) > (greaterPrime - temp)) {
b[k] = greaterPrime;
}
}
}
System.out.println(new String(b, "UTF-8"));
}
}
private static boolean checkPrime(byte n) {
if (n == 1) {
return false;
}
byte i = 2;
while (i < (n / 2)) {
if (n % i == 0) {
return false;
}
i++;
}
return true;
}
private static byte findPrimeGreater(byte n) {
while (!checkPrime(n)) {
n++;
}
return n;
}
private static byte findPrimeSmaller(byte n) {
while (!checkPrime(n)) {
n--;
}
return n;
}
红颜莎娜
相关分类