leetcode菜鸡斗智斗勇系列(5)--- 寻找拥有偶数数位的数字
1.原题:
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/
Given an array nums
of integers, return how many of them contain an even number of digits.
翻译:给定一个整数数组,输出拥有偶数数位的数字的数量。
理论上的输入输出:
Input: nums = [555,901,482,1771]
Output: 1
2.解题思路:
遇到这种需要区别偶奇数的情况,通常都应该想到要用 % 运算符,不过这次我们的目的不是查看数字本身是不是偶数,所以需要用到 to_string(int) 这个函数,可以把 int 转换成string。
然后再用size()来看string的长度,再把长度 % 2 就可以得知是否是偶数。
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;
});
}
};