Find Numbers with Even Number of Digits

Given an array nums of integers, return how many of them contain an even number of digits.

Example 1:

Input: nums = {12,345,2,6,7896}
Output: 2

Approach

Java

public class FindNumEvenNumDigits {
    public static void main(String[] args) {
        int nums[] = { 12345267896 };
        System.out.println(findNumbers(nums));
    }

    // function to check if length of
    // the number is even or not
    static boolean isEven(int a) {
        int cnt = 0;
        while (a > 0) {
            cnt++;
            a /= 10;
        }
        if (cnt % 2 == 0)
            return true;
        return false;
    }

    static int findNumbers(int[] nums) {
        int cnt = 0;
        for (int i = 0; i < nums.length; i++) {
            if (isEven(nums[i])) {
                cnt++;
            }
        }
        return cnt;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

//function to check if length of
//the number is even or not
bool isEven(int a)
{
        int cnt=0;
        while(a)
        {
            cnt++;
            a/=10;
        }
        if(cnt%2==0)
              return true;
        return false;
}
int findNumbers(vector<int>& nums
{
    int cnt=0;
    for(int i=0;i<nums.size();i++)
      {
         
         if(isEven(nums[i]))
             {
              cnt++;
             }  
      }
   return cnt;
}
int main()
{
    vector<intnums ={12,345,2,6,7896};
    cout<<findNumbers(nums);
    return 0;
}


No comments:

Post a Comment