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;
});
}
};
參考:https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/457606/javaPython-3-1-liners.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/45239.html
標籤:其他
上一篇:@程式員,承認吧,都是你的錯!
下一篇:回首2019,展望2020
