在 Python 中查找位数为偶数的数字

pythonserver side programmingprogramming更新于 2025/11/4 5:32:17

假设我们有一个数字列表。我们必须计算位数为偶数的数字。因此,如果数组为 [12,345,2,6,7896],则输出将为 2,因为 12 和 7896 的位数为偶数

为了解决这个问题,我们将遵循以下步骤 −

  • 获取列表并将每个整数转换为字符串
  • 如果字符串的长度为偶数,则增加计数并最终返​​回计数值

示例

让我们看看下面的实现以便更好地理解 −

class Solution(object):
   def findNumbers(self, nums):
      str_num = map(str, nums)
      count = 0
      for s in str_num:
         if len(s) % 2 == 0:
            count += 1
      return count
ob1 = Solution()
print(ob1.findNumbers([12,345,2,6,7897]))

输入

[12,345,2,6,7897]

输出

2

相关文章


有用资源