algoadvance

Leetcode 1295. Find Numbers with Even Number of Digits

Problem Statement

Given an array nums of integers, return how many of them contain an even number of digits.

Clarifying Questions

  1. Range of Elements in Array: What is the range of values for the elements in nums?
    • Answer: Elements can be positive or negative and are within the range given by typical integer bounds in Java.
  2. Array Length: What is the range for the size of the array nums?
    • Answer: The array size can be from 1 to 500.
  3. Data Types: Are all inputs guaranteed to be integers?
    • Answer: Yes, all elements in the array are integers.

Strategy

  1. Counting Function:
    • Create a helper function to count the number of digits in a given number.
  2. Main Function:
    • Iterate through each number in the array.
    • Use the helper function to check the number of digits.
    • Increment a counter for each number that has an even number of digits.
  3. Return Result:
    • Return the final count.

Code

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
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI