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

Arrays: Find Numbers with Even Number of Digits

public class Nodigeven {
    static int even=0;
    static int count=0;
    static int findnodigeven(int[] arr) {
        for(int i=0;i<arr.length;i++) {
            while(arr[i]!=0) {
                arr[i]= arr[i]/10;
                count++;
            }
            if(count%2==0) {
                even++;
            }
        }
return even;
        }
    public static void main(String[] args) {
        int[] arr = {122,255,133,14,15,16};
        System.out.println(findnodigeven(arr));
    }   
}

am getting wrong output i.e : 1 .. can you tell me where i am going wrong here in the code

>Solution :

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

You need to change where you initialize count in your code – it never resets back to 0 and therefore the logic is incorrect for detecting if a number has an even number of digits.

public class Nodigeven {
    static int even = 0;
    static int findnodigeven(int[] arr) {
        for(int i = 0; i < arr.length; i++) {
            int count = 0; // This variable was in the wrong spot!
            while(arr[i] != 0) {
                arr[i] = arr[i] / 10;
                count++;
            }
            if(count % 2 == 0) {
                even++;
            }
        }
        return even;
    }
    public static void main(String[] args) {
        int[] arr = {122,255,133,14,15,16};
        System.out.println(findnodigeven(arr));
    }   
}
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