Skip to content

Latest commit

 

History

History
87 lines (60 loc) · 1.96 KB

File metadata and controls

87 lines (60 loc) · 1.96 KB

English Version

题目描述

给你一个整数数组 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

解法

首先将数组元素转换为字符串,判断字符串长度是否为偶数即可。

Python3

class Solution:
    def findNumbers(self, nums: List[int]) -> int:
        res = 0
        for num in nums:
            res += (len(str(num)) & 1) == 0
        return res

Java

class Solution {
    public int findNumbers(int[] nums) {
        int res = 0;
        for (int num : nums) {
            res += (String.valueOf(num).length() & 1) == 0 ? 1 : 0;
        }
        return res;
    }
}

...