2180. Count Integers With Even Digit Sum

2180. Count Integers With Even Digit Sum #

Problem #

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

Problem Summary #

Given a positive integer num, count and return the number of positive integers less than or equal to num whose digit sum is even.

The digit sum of a positive integer is the result of adding up all the corresponding digits in its digits.

Solution Approach #

  • Simple problem. According to the problem statement, calculate the digit sum of each number. If the sum is even, increment the count by one. Finally, output the count.

Code #

package leetcode

func countEven(num int) int {
	count := 0
	for i := 1; i <= num; i++ {
		if addSum(i)%2 == 0 {
			count++
		}
	}
	return count
}

func addSum(num int) int {
	sum := 0
	tmp := num
	for tmp != 0 {
		sum += tmp % 10
		tmp = tmp / 10
	}
	return sum
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文