LeetCode 1295. Find Numbers with Even Number of Digits 查找数字为偶数的数字 (Easy)

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。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容