Finding numbers with even numbers of digits
Today I’m working through a simple leetcode problem. Given an array of integers, I’m supposed to find the number of integers with even numbers of digits. For example, 1000 has 4 digits, and is even. 100 has 3 digits, and is odd.
Easy enough, I guess. First I create a clone of the array where each integer is converted into a string.
stringNums = nums.map(num=>num.toString());
I declare an empty array to hold the answer, then create a for loop where I call .length on each element of the stringNums array and see if that number % 2 == 0, in which case it is even.
.length when called on a string, if I remember correctly, should return the number of characters it contains.
(The problem only needs to return the number of elements where the digits are even. When I started writing the answer out, I figured I’d need to return a new array. So I guess I could have just created a variable that’s equal to 0 and incremented it each time the condition was met, and then returned that in the end)
In the end, I return the length of the answer array.
Easy.
I hope you learned something, dear reader. I’m not sure that I did.