Count Integers With Even Digit Sum
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given a positive integer num, return the number of positive integersless than or equal to num whose digit sums areeven.
The digit sum of a positive integer is the sum of all its digits.
Examples
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
Solution
Method 1 – Brute Force Digit Sum
Intuition
For each number from 1 to num, calculate the sum of its digits. If the sum is even, count it.
Approach
- Initialize a counter to 0.
- For each integer x from 1 to num:
- Compute the sum of its digits.
- If the sum is even, increment the counter.
- Return the counter.
Code
C++
class Solution {
public:
int countEven(int num) {
int ans = 0;
for (int x = 1; x <= num; ++x) {
int s = 0, t = x;
while (t) { s += t % 10; t /= 10; }
if (s % 2 == 0) ans++;
}
return ans;
}
};
Go
func countEven(num int) int {
ans := 0
for x := 1; x <= num; x++ {
s, t := 0, x
for t > 0 {
s += t % 10
t /= 10
}
if s%2 == 0 {
ans++
}
}
return ans
}
Java
class Solution {
public int countEven(int num) {
int ans = 0;
for (int x = 1; x <= num; x++) {
int s = 0, t = x;
while (t > 0) { s += t % 10; t /= 10; }
if (s % 2 == 0) ans++;
}
return ans;
}
}
Kotlin
class Solution {
fun countEven(num: Int): Int {
var ans = 0
for (x in 1..num) {
var s = 0
var t = x
while (t > 0) {
s += t % 10
t /= 10
}
if (s % 2 == 0) ans++
}
return ans
}
}
Python
class Solution:
def countEven(self, num: int) -> int:
ans = 0
for x in range(1, num + 1):
s = sum(int(d) for d in str(x))
if s % 2 == 0:
ans += 1
return ans
Rust
impl Solution {
pub fn count_even(num: i32) -> i32 {
let mut ans = 0;
for x in 1..=num {
let mut s = 0;
let mut t = x;
while t > 0 {
s += t % 10;
t /= 10;
}
if s % 2 == 0 {
ans += 1;
}
}
ans
}
}
TypeScript
class Solution {
countEven(num: number): number {
let ans = 0;
for (let x = 1; x <= num; x++) {
let s = 0, t = x;
while (t > 0) {
s += t % 10;
t = Math.floor(t / 10);
}
if (s % 2 === 0) ans++;
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(n log n), as we process each number and sum its digits. - 🧺 Space complexity:
O(1), only a constant amount of space is used.