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. Input Size: What is the range of possible sizes for the input array?
    • Assumption: The size of nums can range from 1 to 10,000.
  2. Element Range: What is the range of possible values for the elements in nums?
    • Assumption: The elements in nums are positive integers.
  3. Output: Should the result be printed or returned?
    • Assumption: The result should be returned as an integer.

Strategy

  1. Identify Even Number of Digits:
    • To check if a number has an even number of digits, we can convert the number to a string and check the length of the string.
    • Alternatively, we can use mathematical operations to count the digits without converting to a string.
  2. Counting the Valid Numbers:
    • Iterate through each number in the array, check if it has an even number of digits, and maintain a count.
  3. Return the Count:
    • Return the count after iterating through the array.

Code

#include <vector>
#include <cmath> // for log10

class Solution {
public:
    int findNumbers(std::vector<int>& nums) {
        int count = 0;
        for (int num : nums) {
            // Counting the number of digits without converting to string
            int numDigits = std::floor(std::log10(num)) + 1;
            if (numDigits % 2 == 0) {
                count++;
            }
        }
        return count;
    }
};

Explanation

  1. Loop through Each Number:
    • We iterate through each number in the array nums.
  2. Count Digits:
    • Use std::log10(num) to find the number of digits: log10(num) gives the number of digits minus one for a positive integer, so we add one to get the correct digit count.
  3. Check for Even Digits:
    • If the number of digits is even (numDigits % 2 == 0), we increment our count.
  4. Return Result:
    • Finally, return the count of numbers with an even number of digits.

Time Complexity

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