[Arrays] Find Numbers with Even Number of Digits
Categories: Arrays
Tags: Even
📋 This is my note-taking from what I learned in LeetCode!
Problem
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
- Input: nums = [12,345,2,6,7896]
- Output: 2
-
- Explanation:
-
- 12 contains 2 digits (even number of digits).
-
- 345 contains 3 digits (odd number of digits).
-
- 2 contains 1 digit (odd number of digits).
-
- 6 contains 1 digit (odd number of digits).
-
- 7896 contains 4 digits (even number of digits).
-
- Therefore only 12 and 7896 contain an even number of digits.
Example 2:
- Input: nums = [555,901,482,1771]
- Output: 1
-
- Explanation:
-
- Only 1771 contains an even number of digits.
Constraints:
1 <= nums.length <= 500 1 <= nums[i] <= 105
Hint #1:
How to compute the number of digits of a number?
Hint #2:
Divide the number by 10 again and again to get the number of digits.
Solution
Approach 1
Algorithm:
- Define a function named find_even_digits that takes an array of integers as an argument.
- Initialize a variable count to zero, which will keep track of the number of integers that have an even number of digits.
- Loop through each integer in the array.
- Convert the integer to a string and calculate the length of the string to determine the number of digits in the integer.
- If the number of digits is even, increment the count variable.
- Return the count variable as the result of the function.
def find_numbers(nums: list[int]) -> int:
count = 0
for num in nums:
digits = 0
while num > 0:
digits += 1
num //= 10
if digits % 2 == 0:
count += 1
return count
nums = [12, 345, 6789, 12345]
print(find_numbers(nums))
Approach 2
Algorithm:
- Initialize a variable result to 0.
-
- For each integer num in the input array nums, do the following:
- a. Calculate the number of digits in num using int(math.log10(num)) + 1.
- b. If the number of digits is even, increment result.
- Return result.
import math
def find_numbers(nums: list[int]) -> int:
result = 0
for num in nums:
# Compute the number of digits of the current number
num_digits = int(math.log10(num)) + 1
# Check if the number of digits is even
if num_digits % 2 == 0:
result += 1
return result
nums = [12, 345, 6789, 12345]
print(find_numbers(nums))
Leave a comment