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)