We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count Integers With Even Digit Sum

Difficulty: Easy


Problem Description

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.


Key Insights

  • A digit sum is calculated by summing the individual digits of a number.
  • An even digit sum occurs when the total sum of the digits is divisible by 2.
  • Iterate through all integers from 1 to num and count those with an even digit sum.

Space and Time Complexity

Time Complexity: O(n), where n is the value of num, since we need to check each integer from 1 to num. Space Complexity: O(1), as we use a constant amount of space for counting.


Solution

To solve the problem, we will iterate through each integer from 1 to num. For each integer, we will calculate the digit sum and check if it is even. If it is, we will increment our count. The algorithm primarily uses a loop to evaluate each number and a simple summation to compute the digit sum.


Code Solutions

def count_even_digit_sum(num):
    count = 0
    for i in range(1, num + 1):
        if sum(int(digit) for digit in str(i)) % 2 == 0:
            count += 1
    return count
← Back to All Questions