Find Numbers with Even Number of Digits

(#1295), Easy

Category: Array, Math

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

String Conversion and Digit Count

  • Initialize a variable `count` to 0.
  • Loop through each number in the array `nums`.
  • Convert the number to a string using `.toString()`.
  • Check the length of the string using `.length`.
  • If the length is divisible by 2 (even), increment `count`.
  • After the loop, return `count`.
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