Count Integers With Even Digit Sum - Problem

Given a positive integer num, you need to count how many positive integers from 1 to num (inclusive) have an even digit sum.

The digit sum of a positive integer is calculated by adding all its individual digits together. For example:

  • 123 → digit sum = 1 + 2 + 3 = 6 (even)
  • 45 → digit sum = 4 + 5 = 9 (odd)
  • 8 → digit sum = 8 (even)

Goal: Return the count of all positive integers ≤ num whose digit sums are even.

Input: A positive integer num
Output: An integer representing the count of numbers with even digit sums

Input & Output

example_1.py — Basic Case
$ Input: num = 4
Output: 2
💡 Note: Numbers 1 to 4: 1(sum=1,odd), 2(sum=2,even), 3(sum=3,odd), 4(sum=4,even). Count = 2
example_2.py — Larger Number
$ Input: num = 30
Output: 14
💡 Note: From 1 to 30, the numbers with even digit sums are: 2,4,6,8,11,13,15,17,19,20,22,24,26,28. Total count = 14
example_3.py — Single Digit
$ Input: num = 1
Output: 0
💡 Note: Only number 1 exists, its digit sum is 1 (odd), so count = 0

Constraints

  • 1 ≤ num ≤ 1000
  • num is a positive integer
  • Digit sum is calculated by adding all digits of a number

Visualization

Tap to expand
Count = 0InitializeFor i = 1 to nProcess eachnumberSum digitsCalculatedigit sumIf sum % 2 = 0Count++if evenExample: num = 41Sum: 1 (odd)2Sum: 2 (even)3Sum: 3 (odd)4Sum: 4 (even)Result: 2 numbers with even digit sums
Understanding the Visualization
1
Initialize Counter
Start with count = 0 to track numbers with even digit sums
2
Process Each Number
For each number from 1 to num, extract and sum all digits
3
Check Even/Odd
If digit sum is divisible by 2, increment our counter
4
Return Result
After checking all numbers, return the final count
Key Takeaway
🎯 Key Insight: This is a simulation problem that requires checking each number individually - there's no mathematical shortcut to avoid calculating digit sums
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
28.6K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen