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