Search code examples
javaarrays

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

  • As far as I can tell you have two errors. The first is that you did not reset count to 0 for each iteration of the loop. The second is that you did not check the special case of 0 in the array. 0 is a single digit and thus odd. But since you never enter the while loop, count will remain 0 and even will be incremented.

    public class Nodigeven {
        
        
        static int findnodigeven(int[] arr) {
            
            for (int i = 0; i < arr.length; i++) {
                int count = 0;
    
                // check for 0 value and skip.
                if (arr[i] == 0) {
                    continue;
                }
                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,0, 133, 14, 15, 16 };
            System.out.println(findnodigeven(arr));
        }
    }
    

    If you're interested you and do this without explicitly counting the digits. Use Math.log10() to get the count, again skipping 0 since the log of 0 is undefined. The number of digits in a decimal number N is Math.log10(N)+1. You can use the conditional operator to add 1 or 0 as appropriate to the parity count.

    public class Nodigeven {
        static int even = 0;
        
        static int findnodigeven(int[] arr) {
            int even = 0;
            for (int i = 0; i < arr.length; i++) {
                even += arr[i] != 0 &&
                    (int) (Math.log10(arr[i])+1) % 2 == 0 
                              ? 1 : 0;
            }
            return even;
        }
        
        public static void main(String[] args) {
            int[] arr = { 122, 255,0, 133, 14, 15, 16 };
            System.out.println(findnodigeven(arr));
        }
    }