Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Amount of zeros at the end of an array with recursions

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading