forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-numbers-with-even-number-of-digits.cpp
61 lines (54 loc) · 1.67 KB
/
find-numbers-with-even-number-of-digits.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Time: O(nlog(logm)), n the length of nums, m is the max value of nums
// Space: O(logm)
class Solution {
public:
Solution() {
static const int M = 1e5;
lookup_.emplace_back(0);
int i = 10;
for (; i < M; i *= 10) {
lookup_.emplace_back(i);
}
lookup_.emplace_back(i);
}
int findNumbers(vector<int>& nums) {
return accumulate(nums.cbegin(), nums.cend(), 0,
[this](const auto& x, const auto& y) {
return x + int(digit_count(y) % 2 == 0);
});
}
private:
int digit_count(int n) {
return distance(lookup_.cbegin(),
upper_bound(lookup_.cbegin(), lookup_.cend(), n));
}
vector<int> lookup_;
};
// Time: O(nlogm), n the length of nums, m is the max value of nums
// Space: O(logm)
class Solution2 {
public:
int findNumbers(vector<int>& nums) {
return accumulate(nums.cbegin(), nums.cend(), 0,
[this](const auto& x, const auto& y) {
return x + int(digit_count(y) % 2 == 0);
});
}
private:
int digit_count(int n) {
int result = 0;
for (; n; n /= 10, ++result);
return result;
}
};
// Time: O(nlogm), n the length of nums, m is the max value of nums
// Space: O(logm)
class Solution3 {
public:
int findNumbers(vector<int>& nums) {
return accumulate(nums.cbegin(), nums.cend(), 0,
[](const auto& x, const auto& y) {
return x + int(to_string(y).length() % 2 == 0);
});
}
};