Magicsheet logo

Count Integers With Even Digit Sum

Easy
100%
Updated 6/1/2025

Asked by 1 Company

Count Integers With Even Digit Sum

What is this problem about?

In this coding problem, you are given a positive integer num. You need to count how many integers in the range [1,num][1, num] have a digit sum that is even. The digit sum is calculated by adding all the individual digits of a number. For example, the digit sum of 123 is 1+2+3=61+2+3 = 6, which is even.

Why is this asked in interviews?

This problem is often used in screening rounds at companies like MindTree to test basic programming logic and loop control. It evaluates whether a candidate can correctly extract digits from an integer and handle simple mathematical conditions. While easy, it can also lead to more advanced discussions about "digit DP" or parity properties in number theory.

Algorithmic pattern used

The primary pattern used here is Simulation or Iterative Enumeration. For every number from 1 to num, you implement a helper function to calculate the sum of its digits (using modulo 10 and division). If the sum is divisible by 2, you increment a counter. Since the upper bound for num is typically small (e.g., 1000), an O(numimeslog(num))O(num imes \log(num)) approach is efficient enough.

Example explanation

Let num = 12.

  • 1: Sum 1 (Odd)
  • 2: Sum 2 (Even) -> Count = 1
  • 3: Sum 3 (Odd)
  • ...
  • 9: Sum 9 (Odd)
  • 10: Sum 1 (Odd)
  • 11: Sum 2 (Even) -> Count = 2
  • 12: Sum 3 (Odd) Final count: 2.

Common mistakes candidates make

The most frequent mistake is not handling the digit extraction correctly—specifically, forgetting to update the number inside the extraction loop (n /= 10). Another mistake is including 0 in the count if the problem specifies the range [1,num][1, num]. Some candidates might also misinterpret "even digit sum" as "each digit must be even," which is a completely different condition.

Interview preparation tip

Always look for mathematical shortcuts. In this problem, notice that exactly half of the numbers in most ranges will have an even digit sum. For very large values of num, you could solve this in O(1)O(1) by realizing the parity of the digit sum changes with each increment, with a small adjustment for the final number.

Similar Questions