美文网首页
LeetCode 1295. Find Numbers with

LeetCode 1295. Find Numbers with

作者: LiNGYu_NiverSe | 来源:发表于2020-12-05 00:00 被阅读0次

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。

相关文章

网友评论

      本文标题:LeetCode 1295. Find Numbers with

      本文链接:https://www.haomeiwen.com/subject/rcywwktx.html