Leetcode 1295. Find Numbers with Even Number of Digits
Given an array nums of integers, return how many of them contain an even number of digits.
nums?
nums?
public class Solution {
public int findNumbers(int[] nums) {
int count = 0;
for (int num : nums) {
if (hasEvenNumberOfDigits(num)) {
count++;
}
}
return count;
}
private boolean hasEvenNumberOfDigits(int num) {
int digitCount = 0;
// Handle negative numbers
if (num < 0) {
num = -num;
}
// Count digits
do {
digitCount++;
num /= 10;
} while (num > 0);
return digitCount % 2 == 0;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {12, 345, 2, 6, 7896};
System.out.println(solution.findNumbers(nums)); // Output: 2
}
}
n: Number of elements in the array.d: Number of digits in the largest number.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?