gpt4 book ai didi

java - 递归函数遍历数组直到结束

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:15 25 4
gpt4 key购买 nike

我有一个数组,例如

int[] array = {4,1,1,1,1,4};

前 4 表示有 4 个数字需要计算,后 4 表示我们需要找到运算组合来实现该数字。

我想让循环在到达最后一个 1 时停止,或者通常到达数组中最后一个之前的数字。通常这很容易,但是当所有数字都相同时,最后找到其中一个数字的索引很困难......有建议吗?

我通常使用:

int last_num = integers[integers.length-2];


if(last_num == integers[a]){ System.out.println(Total); )

但是如果last_num = 1,并且integers[a] =1,那么它可以在第一次循环后停止。

如果尝试使用binarySearch查找索引,由于所有数字都相同,也会发生同样的事情。

递归函数(注意,我是 Java 新手,我确信我使用了错误的函数,因为我每次都返回 true,但我的目标是让它运行并打印出我想要的值 - 请暂时原谅):

public static boolean addMoreMore(int a , double b , String c, int[] integers , int target, double possible2, int last_num){
int counter = 0;
char[] symbols1 = {'+' , '-' , '*','/'};
for(int z = 0; z<4; z++){
char operator = symbols1[z];

String what1 = "";
double total1 = 0;

if(operator == '+'){
total1 = b + integers[a];
what1 = c + "+" + integers[a]; //System.out.println(what1);
if(last_num != integers[a]){
//System.out.println("ACTIVATE1");
addMoreMore(a+1 , total1, what1, integers, target, possible2, last_num);
}
else {
if(total1 == target){
System.out.println(what1 + " = " + total1);
}
}
}
else if(operator == '-'){

total1 = b - integers[a];
what1 = c + "-" + Integer.toString(integers[a]);
//System.out.println(what1);

if(last_num != integers[a]){
// System.out.println("ACTIVATE2");
addMoreMore(a+1 , total1, what1, integers, target, possible2, last_num);
}
else {
if(total1 == target){
System.out.println(what1 + " = " + total1);
}
}
}
else if(operator == '*'){
total1 = b * integers[a];
what1 = c + "*" + Integer.toString(integers[a]);
//System.out.println(what1);

if(last_num != integers[a]){
// System.out.println("ACTIVATE3");
addMoreMore(a+1 , total1, what1, integers, target, possible2, last_num);
}
else{
if(total1 == target){
System.out.println(what1 + " = " + total1);
}
}
}
else if(operator == '/'){
total1 = b / integers[a];
what1 = c + "/" + Integer.toString(integers[a]); // System.out.println(what1);
if((b % integers[a]) == 0){

if(last_num != integers[a]){
// System.out.println("ACTIVATE4");
addMoreMore(a+1 , total1, what1, integers, target, possible2, last_num);
}
else {
if(total1 == target){
System.out.println(what1 + " = " + total1);
}
}
}
}
}
return true;
}

最佳答案

正如评论所述,比较数组的索引位置而不是值。

例如:

而不是

if(last_num == integers[a]){ System.out.println(Total); )

尝试

if(integers.length - 2 == a) { System.out.println(Total); }

假设 a 是数组中索引位置的计数变量。

关于java - 递归函数遍历数组直到结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21175220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com