- LeetCode 1295. Find Numbers with
- 1295. Find Numbers with Even Num
- 448. Find All Numbers Disappeare
- LeetCode 448. Find All Numbers D
- 1295. Find Numbers with Even Num
- #448. Find All Numbers Disappear
- LeetCode 448. Find All Numbers D
- 跟我一起刷leetCode算法题6之Find All Numbe
- 448. Find All Numbers Disappeare
- LeetCode之Find Numbers with Even
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). 12包含2位数字(偶数个数字)
345 contains 3 digits (odd number of digits). 345包含3个数字(奇数个数字)。
2 contains 1 digit (odd number of digits). 2包含1位数字(奇数位数)。
6 contains 1 digit (odd number of digits). 6包含1位数字(奇数位数)。
7896 contains 4 digits (even number of digits). 7896包含4位数字(偶数个数字)。
Therefore only 12 and 7896 contain an even number of digits.因此,只有12和7896包含偶数个数字。
Example 2:
Input: nums = [555,901,482,1771]
Output:1
Explanation:
Only 1771 contains an even number of digits.只有1771包含偶数个数字。
Constraints:
- 1 <= nums.length <= 500
- 1 <= nums[i] <= 10^5
Solution:
#solution1
class Solution:
def findNumbers(self, nums: List[int]) -> int:
ans = 0
for n in nums:
digits = len(str(n))
if digits % 2 == 0:
ans += 1
return ans
# solution 2
class Solution:
def findNumbers(self, nums: List[int]) -> int:
ans = 0
for n in nums:
digits = 0
while n:
digits += 1
n = n // 10
if digits % 2 == 0:
ans += 1
return ans
Both solutions are self-explaining. Visit each number and check the number of its digits. If it is even, we add 1 to the result. 两种解决方案都是不言自明的。访问每个数字并检查其位数。如果是偶数,则将结果加1。
网友评论