Find Numbers with Even Number of Digits
The problem asks to find how many integers in the array nums
have an even number of digits.
Python solution:
|
|
Explanation
Initialization: We initialize a
count
variable as 0. This variable will hold the number of integers with an even number of digits.Iterating through the Numbers: We use a
for
loop to iterate through each numbernum
in the givennums
array.Checking Even Number of Digits: Inside the loop, we convert the number to a string using
str(num)
, and then we check the length of this string usinglen()
. If the length is even (len(str(num)) % 2 == 0
), it means the number has an even number of digits, and we incrementcount
by 1.Returning the Result: After the loop, we return the value of
count
, which represents the number of integers with an even number of digits in the given array.
title: Find Numbers with Even Number of Digits excerpt: Basic building block - reducing integer numbers in action. tags: integer-division reduce-value-by-integer-division counter
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] <= 10^5
How to compute the number of digits of a number ?
Divide the number by 10 again and again to get the number of digits.
|
|
Integer division is used to reduce the integer by one number at a time. This is a basic building block that is useful in solving many problems.
Building Blocks
- Integer Division
- Reduce Value by Integer Division
- Counter