#2180

Count Integers With Even Digit Sum

Easy
MathSimulationMathSimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach leverages the fact that the digit sums of consecutive integers alternate between even and odd. Therefore, we can calculate the count of even digit sums directly based on the parity of num.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a counter to zero.
  2. 2Step 2: Loop through each integer from 1 to num.
  3. 3Step 3: Calculate the digit sum for each integer.
  4. 4Step 4: If the digit sum is even, increment the counter.
  5. 5Step 5: Return the counter after the loop.
solution.py9 lines
1# Full working Python code
2
3def count_even_digit_sum(num):
4    count = 0
5    for i in range(1, num + 1):
6        if sum(int(d) for d in str(i)) % 2 == 0:
7            count += 1
8    return count
9

Complexity note: The time complexity is O(n) because we only loop through the integers up to num once, and the space complexity is O(1) since we are using a fixed amount of space regardless of input size.

  • 1The digit sums of consecutive integers alternate between even and odd.
  • 2Counting can be done efficiently without recalculating for every integer.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.