leetcode菜鸡斗智斗勇系列(5)--- 寻找拥有偶数数位的数字

1.原题:

https://leetcode.com/problems/find-numbers-with-even-number-of-digits/java

 

Given an array nums of integers, return how many of them contain an even number of digits.git

翻译:给定一个整数数组,输出拥有偶数数位的数字的数量。数组

 

理论上的输入输出:函数

Input: nums = [555,901,482,1771]
Output: 1 翻译

 

2.解题思路:

遇到这种须要区别偶奇数的状况,一般都应该想到要用 % 运算符,不过此次咱们的目的不是查看数字自己是否是偶数,因此须要用到 to_string(int) 这个函数,能够把 int 转换成string。code

而后再用size()来看string的长度,再把长度 % 2 就能够得知是不是偶数。leetcode

 

class Solution {
public:
int findNumbers(vector<int>& nums) {
return count_if(nums.begin(), nums.end(), [](const auto& a) {
return to_string(a).size() % 2 == 0;
});
}
};get

 

 

引用:https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/457606/javaPython-3-1-liners.string

相关文章
相关标签/搜索