【Python】【难度:简单】Leetcode 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路1:

根据审题,可以看到nums[i]的值介于1到100000之间,可以得出该区间内位数是偶数个数的规律,逐个进行判断;

class Solution(object):
    def findNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        cnt=0
        for i in nums:
            if (i>=10 and i<=99) or (i>=1000 and i<=9999) or i==100000:
                cnt+=1
        return cnt

执行结果:

通过

显示详情

执行用时:24 ms, 在所有 Python 提交中击败了96.86%的用户

内存消耗:12.6 MB, 在所有 Python 提交中击败了25.00%的用户

 

思路2:

将每一位数字转成字符串求长度进行判断;

class Solution(object):
    def findNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        cnt=0
        for i in nums:
            if len(str(i))%2==0:
                cnt+=1
        return cnt

执行结果:

通过

显示详情

执行用时:28 ms, 在所有 Python 提交中击败了94.39%的用户

内存消耗:12.9 MB, 在所有 Python 提交中击败了25.00%的用户

 

思路3:

将每一位数字不断除10计算该数字位数,并判断位数奇偶;

class Solution(object):
    def findNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        cnt=0
        for i in nums:
            tmp=0
            while i:
                i=i//10
                tmp+=1
            if tmp%2==0:
                cnt+=1 
        return cnt

执行结果:

通过

显示详情

执行用时:28 ms, 在所有 Python 提交中击败了94.39%的用户

内存消耗:12.7 MB, 在所有 Python 提交中击败了25.00%的用户

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值