Find Numbers with Even Number of Digits | JavaScript | LeetCode
Leetcode Array Problems | Arrays 101
Let us check the problem statement first: Given an array nums
of integers, return how many of them contain an even number of digits.
Example one:
Example Two:
Now take a look at the constraints:
1 <= nums.length <= 500
This means that the array nums
will have at least 1 element and at most 500 elements. The smallest possible array size is 1, and the largest possible array size is 500.
1 <= nums[i] <= 10<sup>5</sup>
This means that each element nums[i]
in the array nums
will have a value between 1 and 105, inclusive. The smallest possible value for any element is 1, and the largest possible value is 105.
Now let us see the solution (JavaScript)
var findNumbers = function(nums) {
evenNum = 0;
nums.forEach(num => {
if(num.toString().length % 2 == 0){
evenNum ++;
}
})
return evenNum;
};
Submission Detail
Now let's see the solution provided by ChatGPT (Optimized)
var findNumbers = function(nums) {
let evenNum = 0;
nums.forEach(num => {
if (Math.floor(Math.log10(num) + 1) % 2 === 0) {
evenNum++;
}
});
return evenNum;
};
Submission Detail
The above version of the code is the best one (ChatGPT). Here’s why:
Efficiency: The second version uses logarithms to count the digits of a number, which is more efficient than converting the number to a string. The logarithm-based approach avoids the overhead of string conversion and the additional memory usage associated with it.
Readability: The logarithm-based approach is concise and directly conveys the intention of counting digits, making the code easier to read and understand.
Performance: Using
Math.log10(num)
is computationally efficient and leverages the mathematical properties of logarithms to determine the number of digits quickly.
In conclusion, always start by trying to solve problems on your own. Once you've given it your best effort, seek out the best solutions. That's exactly what I did here; I tried my approach first and then used GPT to optimize it.