Find Numbers with Even Number of Digits(#1295)

Category: Array, Math, Foundation

๐Ÿงฉ Problem Statement

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

๐Ÿ“š Examples

Input: nums = [12, 345, 2, 6, 7896]

Output: 2

Explanation: Only 12 and 7896 have an even number of digits.

Input: nums = [555, 901, 482, 1771]

Output: 1

Explanation: Only 1771 has an even number of digits.

๐Ÿง  Approach

โ€ข Initialize a count variable to 0.

โ€ข Traverse the array using a for loop.

โ€ข Convert each number to a string using `.toString()`.

โ€ข Get the length of the string using `.length`.

โ€ข If the length is even (i.e., divisible by 2), increment the count.

โ€ข Return the count.

๐Ÿ’ป Code

var findNumbers = function (nums) {
    let count = 0;

    for (let i = 0; i < nums.length; i++) {
        if (nums[i].toString().length % 2 === 0) {
            count++;
        }
    }

    return count;
};

console.log(findNumbers([12, 345, 2, 6, 7896])); // Output: 2
console.log(findNumbers([555, 901, 482, 1771])); // Output: 1

๐Ÿ“ˆ Complexity

Time: O(n)

Space: O(1)

๐ŸŽฌ Watch Explanation

๐Ÿ“Ž Resources