给你一个整数数组 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%的用户