LeetCode-Python-1295. 统计位数为偶数的数字(数学 + 字符串)

给你一个整数数组 nums,请你返回其中位数为 偶数 的数字的个数。

示例 1:

输入:nums = [12,345,2,6,7896]
输出:2
解释:
12 是 2 位数字(位数为偶数) 
345 是 3 位数字(位数为奇数)  
2 是 1 位数字(位数为奇数) 
6 是 1 位数字 位数为奇数) 
7896 是 4 位数字(位数为偶数)  
因此只有 12 和 7896 是位数为偶数的数字
示例 2:

输入:nums = [555,901,482,1771]
输出:1 
解释: 
只有 1771 是位数为偶数的数字。
 

提示:

1 <= nums.length <= 500
1 <= nums[i] <= 10^5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-numbers-with-even-number-of-digits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:

水题,直接转字符串判断数字长度即可。

时间复杂度:O(NK),N是nums长度,K是max(nums)长度

空间复杂度:O(K)

class Solution(object):
    def findNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res = 0
        for num in nums:
            if len(str(num)) % 2 == 0:
                res += 1
        return res
发布了687 篇原创文章 · 获赞 88 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/103662460