另一个twinoid被定义为一个数组,该数组恰好有两个相邻的偶数值。例如,{3, 3, 2, 6, 7}是一个孪生数组,因为它恰好有两个偶数(2和6),并且它们彼此相邻。下面的数组不是孪生数组。
{3, 3, 2, 6, 6, 7},因为它有three even值。{3, 3, 2, 7, 6, 7},因为偶数值是彼此之间的not adjacent。{3, 8, 5, 7, 3},因为它具有only one even值。我编写Twinoid是为了检查给定的数组是否为twinoid。
public class Twinoid {
public static void main(String args[]) {
System.out.println("The result is: " + isTwinoid(new int[]{3, 3, 2, 6, 7}));
}
public static boolean isTwinoid(int[] a) {
boolean status = false;
int i;
int count = 0;
for (i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) {
count++;
}
}
if (count == 2) {
int j;
for (j = 0; j < a.length; j++) {
if (a[j] % 2 == 0) {
System.out.println(a[j]);
break;
}
}
int nextValue = a[j + 1];
System.out.println(nextValue);
if (nextValue % 2 == 0) {
status = true;
}
} else {
status = false;
}
return status;
}
}发布于 2021-08-13 09:23:57
正如mdfst13所指出的,您不需要扫描数组两次。
实际上,您可能只需要在第一个偶数之后检查下一个int,因为如果它不是偶数,就可以停止。
否则,继续扫描数组的其余部分,如果找到第三个偶数,则可以停止。
public class Twinoid {
/**
* Returns true if the array contains exactly two even values that are adjacent.
*/
public static boolean isTwinoid(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
if (!isEven(array[i])) {
continue;
}
if (!isEven(array[i + 1])) {
return false;
}
return !containsEvenFromIndex(array, i + 2);
}
return false;
}
private static boolean containsEvenFromIndex(int[] array, int i) {
while (i < array.length) {
if (isEven(array[i])) {
return true;
}
i++;
}
return false;
}
private static boolean isEven(int n) {
return n % 2 == 0;
}
}https://codereview.stackexchange.com/questions/117450
复制相似问题