Given a positive integer num
, return the number of positive integers less than or equal to num
whose digit sums are even.
The digit sum of a positive integer is the sum of all its digits.
Example 1:
Input: num = 4 Output: 2 Explanation: The only integers less than or equal to 4 whose digit sums are even are 2 and 4.
Example 2:
Input: num = 30 Output: 14 Explanation: The 14 integers less than or equal to 30 whose digit sums are even are 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.
Constraints:
1 <= num <= 1000
class Solution:
def countEven(self, num: int) -> int:
ans = 0
for i in range(1, num + 1):
t = 0
while i:
t += i % 10
i //= 10
if t % 2 == 0:
ans += 1
return ans
class Solution {
public int countEven(int num) {
int ans = 0;
for (int i = 1; i <= num; ++i) {
int j = i, t = 0;
while (j > 0) {
t += j % 10;
j /= 10;
}
if (t % 2 == 0) {
++ans;
}
}
return ans;
}
}
function countEven(num: number): number {
let ans = 0;
for (let i = 2; i <= num; i++) {
if ([...String(i)].reduce((a, c) => a + Number(c), 0) % 2 == 0) {
ans++;
}
}
return ans;
}
class Solution {
public:
int countEven(int num) {
int ans = 0;
for (int i = 1; i <= num; ++i) {
int t = 0;
for (int j = i; j; j /= 10) t += j % 10;
if (t % 2 == 0) ++ans;
}
return ans;
}
};
func countEven(num int) int {
ans := 0
for i := 1; i <= num; i++ {
t := 0
for j := i; j > 0; j /= 10 {
t += j % 10
}
if t%2 == 0 {
ans++
}
}
return ans
}