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.

Input & Output

Example 1 — Small Number
$ Input: num = 4
Output: 2
💡 Note: Check numbers 1-4: 1(sum=1,odd), 2(sum=2,even), 3(sum=3,odd), 4(sum=4,even). Count of even sums = 2.
Example 2 — Larger Number
$ Input: num = 30
Output: 14
💡 Note: Among numbers 1-30, exactly 14 have even digit sums (like 2,4,6,8,11,13,15,17,20,22,24,26,28,29).
Example 3 — Single Digit
$ Input: num = 9
Output: 4
💡 Note: Numbers 1-9 with even digit sums: 2,4,6,8. Total count = 4.

Constraints

  • 1 ≤ num ≤ 1000

Visualization

Tap to expand
Count Integers With Even Digit Sum INPUT num = 4 Check all integers from 1 to 4: 1 2 3 4 Digit Sum = sum of all digits Even if divisible by 2 Example: 123 --> 1+2+3 = 6 ALGORITHM STEPS 1 Calculate Digit Sum 1-->1, 2-->2, 3-->3, 4-->4 2 Check if Even digit_sum % 2 == 0 ? 3 Count Valid Numbers Increment counter if even 4 Return Count Output total count Calculations: 1: sum=1, odd X 2: sum=2, even OK 3: sum=3, odd X 4: sum=4, even OK Count = 2 FINAL RESULT Valid integers with even digit sum: 2 4 2 has digit sum 2 (even) 4 has digit sum 4 (even) Output: 2 OK - 2 integers found with even digit sums from 1 to 4 Key Insight: For numbers 1 to n, approximately half have even digit sums. The optimal approach iterates from 1 to num, calculates each digit sum by extracting digits (n % 10), and counts those where the sum is divisible by 2. Time: O(n * d) where d is number of digits. TutorialsPoint - Count Integers With Even Digit Sum | Optimal Solution
Asked in
Google 15 Microsoft 12
32.5K Views
Medium Frequency
~15 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