Advertisements
I want to count how many zeros are at the end of the array using recursions. But I’m having problems with an array with all of it’s elements equal to 0 because it’s giving me the wrong answer.
I’ve tried putting the position in the range (0,v.length-1], putting one of the two conditions and not putting said range
Here’s what I’ve done so far
public static int Ejercicio22f(int[] v,int pos){
if(pos<=v.length-1){
if(v.length==0){return 0;}
else if(v.length==1){
if(v[v.length-1]!=0){return 0;}
else{return 1;}
} else{
if(v[pos]==0 && pos>0){return 1+Ejercicio22f(v,pos-1);}
else if(v[0]==0){return v.length;}
else{return 0;}
}
} else{return Ejercicio22f(v, v.length-1);}
}
>Solution :
Try this:
public static int Ejercicio22f(int[] v, int pos) {
if (pos == 0) {
if (v[pos] == 0) {
return 1;
} else {
return 0;
}
} else {
if (v[pos] == 0) {
return Ejercicio22f(v, pos - 1) + 1;
} else {
return 0;
}
}
}
On first run, pass in v.length - 1
as the pos
argument.