Skip to content

Commit 5f1b238

Browse files
authored
Create count-integers-with-even-digit-sum.cpp
1 parent a74a76b commit 5f1b238

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Time: O(logn)
2+
// Space: O(1)
3+
4+
// math
5+
class Solution {
6+
public:
7+
int countEven(int num) {
8+
const auto& parity = [](int x) {
9+
int result = 0;
10+
for (; x; x /= 10) {
11+
result += x % 10;
12+
}
13+
return result % 2;
14+
};
15+
return (num - parity(num)) / 2;
16+
}
17+
};
18+
19+
// Time: O(logn)
20+
// Space: O(1)
21+
// math
22+
class Solution2 {
23+
public:
24+
int countEven(int num) {
25+
const auto& parity = [](int x) {
26+
int result = 0;
27+
for (; x; x /= 10) {
28+
result += x % 10;
29+
}
30+
return result % 2;
31+
};
32+
int result = 0;
33+
for (int i = 1; i <= num; ++i) {
34+
result += static_cast<int>(parity(i) == 0);
35+
}
36+
return result;
37+
}
38+
};

0 commit comments

Comments
 (0)