← All posts

LeetCode 1295: Find Numbers with Even Number of Digits

1 min read

SeriesLeetCodepart 8 of 10
  1. LeetCode Problem 1480: Sum
  2. LeetCode Problem 1672: Solving the Richest Customer Wealth Challenge
  3. Leetcode Question 412: Fizz Buzz - My Simple Solution
  4. LeetCode Question 1342: Number of Steps to Reduce a Number to Zero - My Simple Solution
  5. Solving LeetCode Problem 876: Middle of the Linked List
  6. LeetCode Question 383: Ransom Note Solution Breakdown
  7. LeetCode 977: Squares of a Sorted Array Solution
  8. LeetCode 1295: Find Numbers with Even Number of Digits
  9. LeetCode 485 - Finding Max Consecutive Ones
  10. Is Bitwise & Better than Arithmetic to Determine Even or Odd? Let’s Dive In!
On this page

So, I’ve been diving into LeetCode problems day in and day out, and today I’m going to share a neat little solution for LeetCode question 1295: Find Numbers with Even Number of Digits. You know how it goes - some days you just churn out code while other days you stare at the screen like a total idiot. But hey, let’s crack on with it!

The Problem

The problem is pretty straightforward, and honestly, it’s one of those you can solve while enjoying your coffee. The goal is to find how many numbers in a given array have an even number of digits.

So, here’s the deal:

  • You’re given an integer array nums, and you have to return the count of numbers that have an even number of digits.

My Solution

Here’s the Java solution I whipped up. You can think of it as a classic counting problem, but we’re counting digits instead of things that matter—like pizza toppings or how many bugs we have to fix.

class Solution {
    public int findNumbers(int[] nums) {
        int counter = 0; // Initialize a counter to track numbers with even digits
        for (int num : nums) {
            int digits = 0; // Variable to count the number of digits in the current number
            // Special handling for zero since it doesn't enter the loop
            if (num == 0) {
                digits = 1;
            }
            while (num > 0) { // This loop counts the digits
                num = num / 10; // Divide by 10 to drop the last digit
                digits++; // Increment digit count
            }
            if ((digits & 1) == 0) { // Check if digits are even using bitwise AND
                counter++; // Increment counter if we have an even digit number
            }
        }
        return counter; // Return the total count of even digit numbers
    }
}

Complexity Analysis

Now let’s talk complexity, because, you know, that’s the good stuff.

  • Time Complexity: O(N * D), where N is the number of elements in the nums array and D is the average number of digits in a number. This is because we potentially examine each digit in every number.

  • Space Complexity: O(1) since we only use a fixed amount of space regardless of input size. Just a couple of integers to keep track of our counts.

References