Información del tema
Ingrese un conjunto de números, separados por espacios, para determinar si los números ingresados pueden cumplir con A = B + 2C, y cada elemento solo se puede usar una vez como máximo. Si hay una combinación de números que cumple con las condiciones, genere los tres números A, B y C a su vez, separados por espacios; si no hay una combinación que cumpla con las condiciones, genere 0.
Por ejemplo: entrada 2 3 5 7 salida 7 3 2
codificación
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
public class CheckNumCouple {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
while ((input = br.readLine()) != null) {
String[] numArrStr = input.split(" ");
checkNumsCouple(numArrStr);
}
}
/**
* 检查是否存在满足条件的数字组合
* @param arrs 数组
*/
public static void checkNumsCouple(String[] arrs) {
// 将字符数组转换为Integer数组
Integer[] arr = new Integer[arrs.length];
for (int i=0; i<arrs.length; i++) {
arr[i] = Integer.valueOf(arrs[i]);
}
// 让数组降序排列
// 通过下面的循环,此处排序可以不要
Arrays.sort(arr, new Comparator<Integer>(){
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
// 定义标识,是否有满足条件数字组合
// 0 无;1或其它值 有
int index = 0;
// 循环数组,让等式相等且3个元素的位置不相等
for (int i=0; i<arr.length; i++) {
for (int j=0; j<arr.length; j++) {
for (int k=0; k<arr.length; k++) {
if ((arr[i] == arr[j] + 2*arr[k]) && (i!=j && i!=k && j!=k)) {
index++;
System.out.println(arr[i] + " " + arr[j] + " " + arr[k]);
}
}
}
}
// 无满足条件的数字
if (index == 0) {
System.out.println(0);
}
}
}
Por encima del código
Ingrese 2 3 4 5 7
Salida 7 3 2
Ingrese 2 4 0
Salida 4 0 2
Ingrese 1 2 3
Salida 0